Connor Finn McKelvey
Connor Finn McKelvey

Reputation: 540

Replacing Phone Numbers on Page with Javascript

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

http://jsfiddle.net/2ARgD/2/

$(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

Answers (3)

Ro Yo Mi
Ro Yo Mi

Reputation: 15010

Description

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

enter image description here

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.

Javascript example

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

Grim...
Grim...

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);
});

http://jsfiddle.net/hhGgQ/2/

Upvotes: 0

p.s.w.g
p.s.w.g

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

Related Questions