Reputation: 540
I am trying to replace all instances of a particular phone number in an html document with javascript.
The phone numbers may come in multiple forms:
888-888-8888
(888)-888-8888
(888) 888-8888
$(document).ready(function(){
function p(a,b,element){
if(!element)element=document.body;
var nodes=$(element).contents().each(function(){
if(this.nodeType==Node.TEXT_NODE){
var r=new RegExp(a,'gi');
this.textContent=this.textContent.replace(r,b);
} else {
p(a,b,this);
}
});
}
p('888-888-8888','(999)-999-9999');
p('(888)-888-8888','(999)-999-9999');
p('(888) 888-8888','(999)-999-9999');
});
It successfully replaces all instances of the first form listed about. But Seems to ignore the parentheses. I have tried escaping with a backslash with no luck. My regex skills are not very good so I would really appreciate some help.
Upvotes: 2
Views: 8197
Reputation: 15010
If you're already sure the value is a phone number then you could use this expression which allows any non-numeric delimiter between any of the sections, or even no delimters at all
Regex: ^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})
Replace with: ($1)-$2-$3
To match all instances of a particular number you could use this:
^\D?(888)\D?\D?(888)\D?(8888)
and the same replacement ($1)-$2-$3
.
Input Samples
0001112222
188-818-8818
288-828-8828
(388)-838-8838
(488) 848-8848
Code
<script type="text/javascript">
var re = /^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/;
var sourcestring = "source string to match with pattern";
var replacementpattern = "($1)-$2-$3";
var result = sourcestring.replace(re, replacementpattern);
alert("result = " + result);
</script>
After Replacement
(000)-111-2222
(188)-818-8818
(288)-828-8828
(388)-838-8838
(488)-848-8848
Upvotes: 2
Reputation: 16953
You could use Regex:
$("p").each(function() {
var rep = $(this).text();
rep = rep.replace(/\(?([0-9]{3})\)?[- ]([0-9]{3})[- ]([0-9]{4})/, '($1)-$2-$3');
$(this).text(rep);
});
Upvotes: 0
Reputation: 149050
Because you're passing the string on to create a regular expression, you need to escape the parenthesis:
p('888-888-8888','(999)-999-9999');
p('\\(888\\)-888-8888','(999)-999-9999');
p('\\(888\\) 888-8888','(999)-999-9999');
Another way would be to use a single pattern:
p('(888-|\\(888\\)[- ])888-8888','(999)-999-9999');
Upvotes: 8