jQuery find and replace string

Related searches

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:

$(body).html($(body).html().replace('lollypops', 'marshmellows'));

This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:

  1. search for the string
  2. find the closest parent element
  3. rewrite only the closest parent element
  4. replace this even in attributes, but not all, for example replace it in class, but not in src

In example, I would have structure like this

<body>
    <div>
        <div>
            <p>
               <h1>
                 <a>lollypops</a>
               </h1>
            </p>
            <span>lollypops</span>
        </div>
    </div>
    <p>
       <span class="lollypops">Hello, World!</span>
       <img src="/lollypops.jpg" alt="Cool image" />
    </p>
<body>

In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s. Does anybody know how to do this?

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

Jquery: Find Text and replace, Warning string.replace('string','new string') not replaced all character. You have to use regax replace. For exp: I have a sting old string1, old� The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).

You could do something this way:

$(document.body).find('*').each(function() {
    if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
        $(this).removeClass('lollypops');
        $(this).addClass('marshmellows');
    }
    var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
    var text = $(this).text(); //getting just current node text
    text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
    $(this).text(text); //setting text
    $(this).append(tmp); //re-append 'foundlings'
});

example: http://jsfiddle.net/steweb/MhQZD/

.replaceWith(), May be an HTML string, DOM element, array of DOM elements, or jQuery object. A function that returns content with which to replace the set of matched� Simple jQuery code snippet to replace all occurrences of characters (or strings) within a string. It could be used to find and replace all substrings found inside a string. Don’t forget to leave

Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.

$('.hightlight').each(function(){
    //highlight_words('going', this);
    var high = 'going';
    high = high.replace(/\W/g, '');
    var str = high.split(" ");
    var text = $(this).text();
    text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
    $(this).html(text);
});

.replaceAll(), A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. The .replaceAll() method is similar to .replaceWith() � Below is simple jQuery code snippets to replace all the dots (.) present on HTML page and then replace it with hyphen. Earlier I had posted about jQuery solution to substring, split string, trim string and about all string functions, And In this post, see jQuery/JavaScript replace function in action with example.

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

JavaScript String replace() Method, To replace all occurrences of a specified value, use the global (g) modifier (see " More Examples" below). Read more about regular expressions in our RegExp� How to find a string and replace it with some other string. We can achieve this by using a Regular Expression that provides us the text replace functionality with its string method: replace() which replaces the specified string with the desired word or substring thereby modifying the original string.

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>

jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

replace returns a string, it does not perform in place changes. And even then, the text would be set to the element automatically. And even then, the text would be set to the element automatically. – Felix Kling May 30 '11 at 13:58

You would create a RegExp object from a string: str = str.replace(new RegExp('"_0x69b9[' + i + ']"', 'g'), _array[i]);. However, consider if you instead can use (\d+) in the pattern to match any number and catch it for lookup in a replacement function, that way you could replace all instances in one replacement instead of doing 101 replacements.

version added: 1.2 .replaceWith ( newContent ) newContent. Type: htmlString or Element or Array or jQuery. The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object.

div - jquery replace text in string Jquery: Find Text and replace (6) I was looking for something similar and I use code that Doug Owings posted, but my text had some br tags and the code was erasing it.

Comments
  • There's an excellent well-written plugin for replacing text. jquery-replacetext-plugin. The plug-in replaces text leaving all tags and attributes untouched. You can also find a nice tutorial for this plug-in at spotlight-jquery-replacetext
  • I know, unfortunately I can't do this on server side. Also, the solution you suggested is unsuitable for me, as I don't know where exactly the string will be. It may be in <span>, it may be in <h4> and so on...
  • Then you could try $("*"), but I wouldn't recommend it.
  • I think the quotes around the string variable in the 'replace' function need to be removed.
  • This is a 4 year old and already answered question, but the problem was that I could not do what you are suggesting.
  • This answer completely ignores the OP's specification: "I want to replace all the occurrences of this string... The problem is that I don't know where exactly the text is."