Reputation: 103
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);
Upvotes: 0
Views: 90
Reputation: 382122
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}/
)
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>");
});
Upvotes: 1