Don Boots
Don Boots

Reputation: 2166

Custom RegEx needed

Using javascript, I need to parse the HTML of a page and replace all occurrences of ABC with ABC that occur within a content block such as <p>ABC Company lorem ipsum</p> would be changed to <p><span class="abc">ABC</span> Company lorem ipsum</p> but mailto:[email protected] would stay the same.

So pretty much replace ABC anywhere that is preceded by a space or quote, but obviously I would like to make it a little more generic. Perhaps the expression would say when it is not preceded/followed by [a-zA-z].

What I have so far:

<script type="text/javascript">
    $(document).ready(function() {
        $('body').find('div').each(function(i, v) {
            h = $(v).html();

            if (h.indexOf('abc') > 0) {
                h = h.replace('abc', '<span class="abc">abc</span>');
                $(v).html(h);
            }
        });
    });
</script>

Upvotes: 2

Views: 88

Answers (2)

beveradb
beveradb

Reputation: 128

This is not a very efficient thing to do (loop through all div tags in the DOM and apply a regex to each one) but since I don't know what constraints you have or what situation you are using this code in, I'll just assume there's a good reason you're doing this client-side in this way.

Anyway, this regex seems to match your requirements (albeit not very well defined requirements):

h = h.replace(/([^A-Z])(ABC)([^A-Z])/gi, '$1<span style="color: red">$2</span>$3');

Fiddle here: http://jsfiddle.net/czJFG/

Upvotes: 1

Kevin B
Kevin B

Reputation: 95022

I suggest going about it a different way that preserves data and events on the elements and doesn't interfere with attributes on said elements.

 $("body div").find("*").addBack().contents().filter(function(){
     return this.nodeType === 3;
 }).each(function() {
     $(this).parent().html(this.nodeValue.replace(/abc/g, '<span  class="abc">abc</span>'));
 })

http://jsfiddle.net/hrEyC/1/

Note, requires jQuery 1.9+ due to use of .addBack(), for older versions replace with .andSelf()

Upvotes: 1

Related Questions