Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace all occurrences of a string in an html page

I'm working on a project where I need to replace all occurrences of a string with another string. However, I only want to replace the string if it is text. For example, I want to turn this...

<div id="container">
  <h1>Hi</h1>
  <h2 class="Hi">Test</h2>
  Hi
</div>

into...

<div id="container">
  <h1>Hello</h1>
  <h2 class="Hi">Test</h2>
  Hello
</div>

In that example all of the "Hi"s were turned into "Hello"s except for the "Hi" as the h2 class. I have tried...

$("#container").html( $("#container").html().replace( /Hi/g, "Hello" ) )

... but that replaces all occurrences of "Hi" in the html as well

like image 645
Calebmer Avatar asked Aug 03 '14 21:08

Calebmer


4 Answers

This:

$("#container").contents().each(function () {
    if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/Hi/g, "Hello")
    if (this.nodeType === 1) $(this).html( $(this).html().replace(/Hi/g, "Hello") )
})

Produces this:

<div id="container">
    <h1>Hello</h1>
    <h2 class="Hi">Test</h2>
    Hello
</div>

jsFiddle example

like image 71
j08691 Avatar answered Nov 15 '22 03:11

j08691


Nice results with:

function str_replace_all(string, str_find, str_replace){
try{
    return string.replace( new RegExp(str_find, "gi"), str_replace ) ;      
} catch(ex){return string;}}

and easier to remember...

like image 27
Cyril Jacquart Avatar answered Nov 15 '22 05:11

Cyril Jacquart


 replacedstr = str.replace(/needtoreplace/gi, 'replacewith');

needtoreplace should not rounded by '

like image 8
Saurabh Chandra Patel Avatar answered Nov 15 '22 03:11

Saurabh Chandra Patel


//Get all text nodes in a given container
//Source: http://stackoverflow.com/a/4399718/560114
function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /\S/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

var textNodes = getTextNodesIn( $("#container")[0], false );
var i = textNodes.length;
var node;
while (i--) {
    node = textNodes[i];
    node.textContent = node.textContent.replace(/Hi/g, "Hello");
}

Note that this will also match words where "Hi" is only part of the word, e.g. "Hill". To match the whole word only, use /\bHi\b/g

like image 3
Matt Browne Avatar answered Nov 15 '22 05:11

Matt Browne