51

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.

alex
  • 479,566
  • 201
  • 878
  • 984
Developer
  • 2,987
  • 10
  • 40
  • 51
  • 1
    possible duplicate of [How to replace a block of HTML with another block of HTML using jQuery](http://stackoverflow.com/questions/2734174/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 – Pekka Feb 03 '11 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. – Xhalent Feb 03 '11 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 :) – Developer Feb 03 '11 at 16:50

7 Answers7

91

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.

Scoobler
  • 9,696
  • 4
  • 36
  • 51
  • Code that worked just fine, Thanks scoobler. jQuery(function($) { var replaced = $("body").html().replace(/12212-522-1212/ig,'2121-2121-0000'); $("body").html(replaced); }); – Developer Feb 06 '11 at 22:41
  • 4
    I don't think this is quite effective... we should lookup for a better solution guys! – Tom Roggero Oct 02 '12 at 16:07
  • 13
    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. – Sumit Gupta Jul 20 '15 at 11:04
  • 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. – Erdi Jan 28 '17 at 18:40
  • 1
    Yea, doing this re-triggers scripts on the page; not a general solution for anything but the most simple cases. – Lucent Fox Jan 31 '17 at 01:38
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.

dmcb
  • 701
  • 5
  • 6
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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    The code at your link handles *almost* all cases. For me, it was borking on `
    ` 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.
    – bishop Sep 20 '14 at 19:01
  • 1
    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](https://github.com/padolsey/findAndReplaceDOMText) -- heavier weight, but covers all the corner cases I could find. – bishop Sep 22 '14 at 00:58
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); });

Alex Grande
  • 7,929
  • 1
  • 26
  • 30
3
$("#elementID").html("another string");

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

  • 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. – Developer Feb 03 '11 at 12:58
  • So you want to search the entire HTML tree for a string, and replace that? – vicvicvic Feb 03 '11 at 13:00
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);
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;
    }
});
bishop
  • 37,830
  • 11
  • 104
  • 139