Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text in HTML page with jQuery

Tags:

jquery

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.

like image 525
Developer Avatar asked Feb 03 '11 12:02

Developer


People also ask

How do you replace an element with another in jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.


1 Answers

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.

like image 177
Scoobler Avatar answered Sep 20 '22 01:09

Scoobler