user3542686
user3542686

Reputation:

regex match in body tag: then add class to all elements containing the matches

This is my body:

<div>http://www.example.com</div>
<span>http://www.mywebsite.com</span><br>
<b>http://www.domain.com</b>

This is my simple regex (works):

document.body.innerHTML.match(/(http|https|ftp):\/\/(?:www\.)?([a-z]|\d|-)+\.(?:([a-z]|-)+\.)*?(com|net|org)(?:\/)?/ig);


How can I add a class to all elements that contain the matches in javascript or jquery? Example:

<div class="matchClass">http://www.example.com</div>
<span class="matchClass">http://www.mywebsite.com</span><br>
<b class="matchClass">http://www.domain.com</b>


DEMO

Upvotes: 1

Views: 324

Answers (4)

guest271314
guest271314

Reputation: 1

Try

$.each(myMatch, function(k, v) {
    $("body *:contains(" + v + ")").addClass("matchClass")
})

jsfiddle http://jsfiddle.net/guest271314/cz6owdxx/3/

Upvotes: 1

vks
vks

Reputation: 67968

(>(http|https|ftp):\/\/(?:www\.)?([a-z]|\d|-)+\.(?:([a-z]|-)+\.)*?(com|net|org)(?:\/)?)

You can try this.Repalce by class="matchClass"$1.

See demo.

http://regex101.com/r/hQ1rP0/16

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59252

Use this regex

/<(.+)>((http|https|ftp):\/\/(?:www\.)?([a-z]|\d|-)+\.(?:([a-z]|-)+\.)*?(com|net|org)(?:\/)?)<\/(.+)>/ig

And replace with

<$1 class="matchClass">$2<$7>

DEMO

Upvotes: 1

Okky
Okky

Reputation: 10466

Are you looking for something like

$('body').children()
    .filter(function () {
    return this.innerHTML.match(/(http|https|ftp):\/\/(?:www\.)?([a-z]|\d|-)+\.(?:([a-z]|-)+\.)*?(com|net|org)(?:\/)?/ig);
}).addClass('matchClass');

JSFiddle

Upvotes: 1

Related Questions