52

How do I replace any string in jQuery?

Let's say I have a string "-9o0-9909" and I want to replace it with another string.

3
  • 1
    possible duplicate of How to replace a block of HTML with another block of HTML using jQuery before asking a question, it is good to check out the automated suggestions the system makes when entering a question title Commented Feb 3, 2011 at 12:49
  • can you elaborate please on why you think jquery is the way to go - the answers so far might be off track. Commented Feb 3, 2011 at 13:02
  • I can change the text in c# page, javascript and database and html pages, but I was thinking if it's possible to achieve that using jquery after page load. I am trying to save sometime and learn something new :) Commented Feb 3, 2011 at 16:50

7 Answers 7

92

You could use the following to replace the first occurrence of a word within the body of the page:

var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);

If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g:

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

If you wanted a one liner:

$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));

You are basically taking all of the HTML within the <body> tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.

See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.

Sign up to request clarification or add additional context in comments.

5 Comments

Code that worked just fine, Thanks scoobler. jQuery(function($) { var replaced = $("body").html().replace(/12212-522-1212/ig,'2121-2121-0000'); $("body").html(replaced); });
I don't think this is quite effective... we should lookup for a better solution guys!
This solution is not good, because it is changes the HTML DOM. it is replacing complete HTML, so everything on page was re-inserted, it is fine for simple site, but if you have lot of javascript they will get broken, as DOM is changed.
Apart from being a good solution, $("body").html() will not have body tag. If you plan to replace something on body tag or it's attributes use outerHTML.
Yea, doing this re-triggers scripts on the page; not a general solution for anything but the most simple cases.
57

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

2 Comments

Yup this one didn't break javascript, while the other one did break javascript, big ups!
Hello, it does not work for me with my example jsfiddle.net/xpcf49mh
12

...I have a string "-9o0-9909" and I want to replace it with another string.

The code below will do that.

var str = '-9o0-9909';

str = 'new string';

Jokes aside, replacing text nodes is not trivial with JavaScript.

I've written a post about this: Replacing text with JavaScript.

2 Comments

The code at your link handles almost all cases. For me, it was borking on <br /> in the set (child is null), and it also would inexplicably crash on splitText now and again with "split offset exceeds text node length". Also, "canvas" is misspelled as "cavas". Still, +1 though.
You're welcome. I liked how short and easy to follow your code was, I just couldn't get it to adapt to my use case. I ultimately went with padolsey's findAndReplaceDOMText library -- heavier weight, but covers all the corner cases I could find.
7

The html replace idea is good, but if done to the document.body, the page will blink and ads will disappear.

My solution:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

1 Comment

Necromancing here, but this solution is the only one that was effective in my use case, thanks, Alex.
3
$("#elementID").html("another string");

http://api.jquery.com/html/

2 Comments

they are not always same id it could be different class name or id name. If I had just 1 class name or id name it wouldn't be hard but it's random most of the time.
So you want to search the entire HTML tree for a string, and replace that?
2
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

for variable:

var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);

Comments

2

Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.

In this sample usage, I replace all text inside a <div id="content"> that looks like a US telephone number with a tel: scheme link:

findAndReplaceDOMText(document.getElementById('content'), {
    find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
    replace:function (portion) {
        var a = document.createElement('a');
        a.className = 'telephone';
        a.href = 'tel:' + portion.text.replace(/\D/g, '');
        a.textContent = portion.text;
        return a;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.