Hi Guy’s Welcome to Proto Coders Point. In this Article let’s check out How to remove brackets () from Phone Number String, With Java & JavaScript Code Example.
Java & JavaScript Code to check if phone number string contains () brackets and remove the brackets
Example:
+91 (123) 867 456 ---> +91 123 867 456
Java Code
public static void main(String[] args) { String phoneNo = "+91 (123) 867 456"; Boolean bool = false; if(phoneNo.contains("(") || phoneNo.contains(")")){ bool = true; } if(bool){ String newphoneno = phoneNo.substring(0,4) + phoneNo.substring(5,8) + phoneNo.substring(9,phoneNo.length()); System.out.println(""+newphoneno); //use replaceAll if you want to remove all empty spaces from string. System.out.println(""+newphoneno.replaceAll("\\s", "")); } }
use replaceAll(“\s”, “”) if you want to remove all empty spaces from string.
JavaScript Code
let phoneNo = "+91 (123) 867 456"; let bool = false; if(phoneNo.includes("(") || phoneNo.includes(")")){ bool = true; } if(bool){ var newphoneno = phoneNo.substring(0,4) + phoneNo.substring(5,8)+phoneNo.substring(9,phoneNo.length); } console.log(newphoneno) //use replace with regex if you want to remove all empty spaces from string. console.log(newphoneno.replace(/\s+/g,''))
Here to remove spaces between the phone number string I am using replace with regular expression.