Jquery to find a name on html page and add hyperlink
Here is my example: I have a a website that contains the following:
<body>
Jim Nebraska zipcode 65437
Tony lives in California his zipcode is 98708
</body>
I would like to be able to search for zip codes on the page and wrap them with hyperlinks like:
<body>
Jim Nebraska zipcode <a href="/65437.htm">65437</a>
Tony lives in California his zipcode is <a href="/65437.htm">98708</a>
</body>
Could I use a regex selector to find the string and then wrap the string, or replace it with the new hyperlink?
I am new to Jquery and looking for开发者_JS百科 someone to point me in the right direction.
Thank you,
Mike
You can use replace method on html:
$('body').html().replace(/\s(65437)\s/g, '<a href=...' + $1 + '</a>');
UPDATE: obviously this example searches only for one specific zip code, but you can adapt the statement by using an array of zip codes and performing a replacement for each code.
this is basically the same as mamoo and Jim posted
slight modifications to the expression and using function instead of $1 for some reason with firebug I get an error trying to use $1
var s = "Jim Nebraska zipcode 65437\nTony lives in California his zipcode is 98708";
// var s = "12345 should be but not this 22 or this 9999999 here is a zip 44444, and then some more content and another one 34366 and so on";
var result = s.replace(/(\b\d{5}-\d{4}\b)|(\b\d{5}\b)/g, function (thisMatch) {
return "<a href='/" + thisMatch + ".htm'>";
});
this still will not handle leaving a 5 digit street address alone, i.e. 12345 Main St. will end up with a link to 12345
UPDATE: changed the regex to avoid greedy handling of 9999999
from: /(\d{5}-\d{4})|(\d{5})/g
to: /(\b\d{5}-\d{4}\b)|(\b\d{5}\b)/g
seems to leave the 9999999 alone as desired
精彩评论