Kirankumar Kirankumar - 5 months ago 16
Javascript Question

Regex operation to replace dynamic word/value from string

I am working with phone directory app in phonegap
I need some javascript operation on mobile number
for example if I have added country code for

Denmark 45


Now I have to check if any mobile number contain
45
in starting of it like
4572342245


Then I wants to remove country code and save it in another field like

CCode Mobile
45 72342245


I have done it with

var numwithcode = "4572342245";
var newNumber = numwithcode .replace(/^45+/i, '');

alert(newNumber); //72342245


Same thing I want to do with, for e.g.
Australia 61
then

var numwithcode = "6172342245";
var newNumber = numwithcode.replace(/^61+/i, '');

alert(newNumber); //72342245


What I want is to set this condition dynamic for any selected country code

for e.g.

var countrycodehere = document.getElementById("countrycodefield").value;
var numwithcode = "6172342245";
var number = newNum.replace(/^countrycodehere+/i, '');

alert(number);


But, i failed with most of the testing I was doing for this.

Thanks

Answer

Creating a regex from a string can be done with

var re = new RegExp( string );

So you could do something like this:

var countrycodehere = document.getElementById("countrycodefield").value,
    numwithcode = "6172342245",
    re = new RegExp( countrycodehere ),
    number;

number = numwithcode.replace(re, ''),

alert(number);

Notice that the + won't get added, and it shouldn't. Because it meant that repetitions of the last digit in the area code would also be removed.

function doAction() {

  var countrycodehere = document.getElementById("countrycodefield").value,
      numwithcode = document.getElementById("phonefield").value,
      re = new RegExp( countrycodehere ),
      number;

  number = numwithcode.replace(re, ''),

  alert(number);
}
<!DOCTYPE html>
<html>
<body>

<form>
Phone number: <input id="phonefield" type="text" value="6172342245"/><br/>
Area code: <input id="countrycodefield" type="text"/><br/>
<button onclick="doAction()">Process</button>
</form>

</body>
</html>