[removed] replace() all but only outside html tags

后端 未结 2 1579
南方客
南方客 2020-12-21 07:18

I have an autocomplete form and when showing the results matching the user\'s search string, I want to highlight the search string itself. I plan to do this by wrapping any

相关标签:
2条回答
  • 2020-12-21 07:50

    Parse the HTML and find all text nodes in it, doing the replace in all of them. If you are using jQuery you can do this by just passing the snippet to $() which parses it in a Document Fragment, which you can then query or step over all elements and find all the .text() to replace.

    0 讨论(0)
  • 2020-12-21 08:00

    Your code should look like this:

    var searchWord = 'pa';
    var originalString = 'The pattern to <span class="something">be replaced is pa but only outside the html tag</span>';
    
    var regEx = new RegExp("(" + searchWord + ")(?!([^<]+)?>)", "gi");
    
    var output = originalString.replace(regEx, "<strong>$1</strong>");
    
    alert(output);
    

    Source: http://pureform.wordpress.com/2008/01/04/matching-a-word-characters-outside-of-html-tags/

    0 讨论(0)
提交回复
热议问题