0

I want to match certain numbers from the page and the regex I created is /^(0 ?){1}([1-8] ?){1}(\d ?){9}$/ and it works fine in online regex tester tool. However, when I put it in my javascript function for some reason the regex matching with ^ & $ is not working in my code.

var regex = /^(0 ?){1}([1-8] ?){1}(\d ?){9}$/; 
var text = $("body:first").html();
text = text.replace(regex, "<a href=\"tel:$&\">$&</a>");

$("body:first").html(text);

Example at JSFiddle

5
  • 2
    Do you understand why pasting an URL wasn't possible ? Because a question should be self sufficient, the fiddle should be a complement, not replace the relevant code. Commented Feb 27, 2014 at 16:45
  • 1
    BTW it's very hard to get what your question is, apart that it "is not working". Commented Feb 27, 2014 at 16:47
  • Sorry I din't knew that I had to paste the code in...I am new to this site.....I'll try to explain the question again Commented Feb 27, 2014 at 16:49
  • 1
    Because .html() returns the html tags and not just the inner text and you have RegEx start and end of string anchors, so nothing will ever match. Try using $.trim($("body:first").text()) or remove the anchors altogether. Commented Feb 27, 2014 at 16:50
  • P.S. (0 ?){1} is the same as (0 ?). The {1} is not needed. Commented Feb 27, 2014 at 16:51

1 Answer 1

1

As you use the regular expression in replace, the start and end markers make no sense. Because you don't try to replace the whole string (which is the content of the body).

Change

var regex = /^(0 ?){1}([1-8] ?){1}(\d ?){9}$/; 

to

var regex = /(0 ?){1}([1-8] ?){1}(\d ?){9}/;

(or /(0 ?)([1-8] ?)(\d ?){9}/)

Demonstration

If you wanted to ensure you changed a whole cell, you could have looked for > and < but the cleanest solution would have been this :

var regex = /^(0 ?)([1-8] ?)(\d ?){9}$/; 
$('td').html(function(_,h){
    return h.replace(regex, "<a href=\"tel:$&\">$&</a>");
});

Demonstration

Sign up to request clarification or add additional context in comments.

3 Comments

Basically what I want to do is look for phone number on page eg. 08457404400 and then hyperlink it. Hence according to the requirement criteria I created the regex. However if I dont put ^ and $ on regex it matches any numbers even though the number is hort in length
the above will only work on the cell I need to read entire DOM and find out the matching number
This operates on all cells. If you want it to check other types of elements, just enrich the selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.