Replace words in the body text
Is there a way to replace the normal text within a table element that is placed within the body of the HTML? Like replacing «hello» with «hi»? Please only use JavaScript without jQuery.
the body has a div and within that a table, then i would like to replace some normal text not code like replacing («hello») with («hi»)
most solutions below will destroy all events and the whole dom structure if word being replaced happened to be class name, tag name or anything in html
It looks like both question and answers are wrong. It asks how to replace words and not chars. Such as replacement of this hello, this is a text randomTexthello should be hi, this is a text randomTexthello . However, all other answers here replacing the chars instead of words.
11 Answers 11
To replace a string in your HTML with another use the replace method on innerHTML:
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
Note that this will replace the first instance of hello throughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution — for better results, try restricting the scope of your replacement by targeting your code using document.getElementById or similar.
To replace all instances of the target string, use a simple regular expression with the g lobal flag:
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
It can be more complicated with extended characters — what encoding is your document in? Are you sure that the character is an ü, and not ü for example.
you didn’t copy my code accurately 😉 make sure you’ve got innerHTML on both sides of the statement, i.e: document.body.innerHTML = document.body.innerHTML.replace(‘ü’, ‘n’);
FYI — Bug in the first comment is: set window.onload = clear; without the parentheses «()». When you write clear() then you actually execute the function, but you only want to assign the function to the onload-handler
Note that using innerHTML is generally considered bad these days: slideshare.net/x00mario/the-innerhtml-apocalypse
I ended up with this function to safely replace text without side effects (so far):
function replaceInText(element, pattern, replacement) < for (let node of element.childNodes) < switch (node.nodeType) < case Node.ELEMENT_NODE: replaceInText(node, pattern, replacement); break; case Node.TEXT_NODE: node.textContent = node.textContent.replace(pattern, replacement); break; case Node.DOCUMENT_NODE: replaceInText(node, pattern, replacement); >> >
It’s for cases where the 16kB of findAndReplaceDOMText are a bit too heavy.
very elegant, is it necessary to keep two cases separate? one for ELEMENT_NODE and the other for DOCUMENT_NODE. Also, there seem to have many other nodetypes, does that mean other types don’t matter?
@B.Mr.W. i don’t remember why i made the cases so explicit. for the question, theses types are sufficient. mind, that some of the types are xml-specific.
Nice! Does node.textContent.replace() do a simple or a regexp-based search, and (how) can it be used on patterns that span several lines? My goal is to remove 2 buttons from a form (phpbb forum reply editor).
The function below works perfectly for me:
// Note this *is* JQuery, see below for JS solution instead function replaceText(selector, text, newText, flags) < var matcher = new RegExp(text, flags); $(selector).each(function () < var $this = $(this); if (!$this.children().length) $this.text($this.text().replace(matcher, newText)); >); >
function replaceAllText() < replaceText('*', 'hello', 'hi', 'g'); >$(document).ready(replaceAllText); $('html').ajaxStop(replaceAllText);
You can also use do a direct replacement like so:
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
But be careful with it since it may affect the tags, css and scripts as well.
EDIT: As for a pure JavaScript solution use this method instead:
function replaceText(selector, text, newText, flags)
How would one go about replacing all text in a specific tag (like
or ) with some other text?
This does not work correctly. Consider this:
hello world
. hello does not get replaced.
Sometimes changing document.body.innerHTML breaks some JS scripts on page. Here is version, that only changes content of text elements:
function replaceRecursively(element, from, to) < if (element.childNodes.length) < element.childNodes.forEach(child =>replaceRecursively(child, from, to)); > else < const cont = element.textContent; if (cont) element.textContent = cont.replace(from, to); >>; replaceRecursively(document.body, new RegExp("hello", "g"), "hi");
I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.
To make it work correctly I used a library to get this done.
The library has an awesome API. After including the script I called it like this:
findAndReplaceDOMText(document.body, < find: 'texttofind', replace: 'texttoreplace' >);
This was the only solution that worked for my issue. I needed to use REGEX to find and replace phone numbers across an entire site and other answers here would break my DOM events.
I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.
So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:
var search = "search string"; var replacement = "replacement string"; document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)
While using innerHTML.replace will work and is pretty fast, this will break the DOM state.
You can replicate this by setting «autofocus» on an input field and then changing innerHTML on body, it will loose focus.
A less destructive approach is:
// retrives all childNodes of body var childNodes = document.body.childNodes; // start replacing replaceInNodes(childNodes, "search", "replace"); function replaceInNodes(nodes,search,replace) < // iterate through all nodes for (var i = 0; i < nodes.length; i++) < var curNode = nodes[i]; // if the node has attributes, let us look at those // i.e. we want to change "John" in the input placeholder to "Peter" - if (curNode.attributes !== undefined) < var curNodeAttributes = curNode.attributes; for (var ii = 0; ii < curNodeAttributes.length; ii++) < // replace attribute values curNodeAttributes[ii].nodeValue = curNodeAttributes[ii].nodeValue.replace(search, replace); >> // It is a "TEXT_NODE" // i.E. John if (curNode.nodeType === Node.TEXT_NODE) < curNode.data = this.injectIntoString(curNode.data); >// It is a "ELEMENT_NODE", meaning we need to go deeper if (curNode.nodeType === Node.ELEMENT_NODE) < this.replaceInNodes(curNode.childNodes); >> >
Note: I am the author of said link
Replace HTML page with contents retrieved via AJAX
Do you think it is possible ? I’ve already tried to give the html tag an id and doing $(id).replace(data); with no success. Don’t ask me why, but that is what I need (I’m working with a special «mashup builder» site. it is a long story). EDIT : I forgot to say that scripts in the received content have to be executed, even external scripts included using .
I’d be really interested to find out more about the requirements. I can’t think of anything that would require such a thing.
It seems to work with normal JavaScript(I am using Chrome). document.getElementsByTagName(‘html’)[0].innerHTML = ‘Input HTML here’;
7 Answers 7
The simplest way is to set the new HTML content using:
document.open(); document.write(newContent); document.close();
Please notice that this method works exactly as requested, but it does not update browser history. If you click back button in your browser after «document.write()» action, you won’t go back to the page before redirect, you will go to the one before it.
try this with jQuery:
Here’s how to do it in Prototype: $(id).update(data)
But document.getElementById(id).innerHTML=data should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.
document.getElementById(id).innerHTML = ajax_response
It requires jQuery first. It’s not good option, if you need it done immidately, without loading external libs.
Can’t you just try to replace the body content with the document.body handler?
blablabla
Just use the document.body to replace the body.
This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the ‘document.’ are capable of doing so.
An example with javascript scripting inside it:
blablabla
This way you can do javascript scripting inside the new content. Don’t forget to escape all double and single quotes though, or it won’t work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.
Bare in mind that server side scripting like php doesn’t work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.
JS replace only text without html tags and codes
I want to replace some words of the document without changing any html tags or js codes. Basically what I do is; document.body.innerHTML = document.body.innerHTML.replace(‘lorem’,’new lorem’); But this code will replace any ‘lorem’. I want to avoid tags like;
2 Answers 2
Walk the DOM, and .replace() the values of text nodes.
walk(document.body, function(node) < var text = node.data.split("foo"), parent = node.parentNode, i = 1, newNode; parent.insertBefore(textNode(text[0]), node); for (; i < text.length; i += 2) < (newNode = document.createElement("b")) .appendChild(textNode("bar")); parent.insertBefore(newNode, node); parent.insertBefore(textNode(text[i]), node); >parent.removeChild(node); >); function textNode(txt)
Thank you. It works great. There is only one thing, I can’t work html tags with replace. I want to do replace(/foo/g, «bar«); but it doesn’t affect because of node.data
@kentilyuk: I thought you didn’t want to replace any elements. The DOM is not a string, so no, that won’t work. What do you actually need to do?
@kentilyuk: So you’re saying you want to wrap the matched text in an element? Again, the DOM is not a string. We won’t be using HTML markup to accomplish this.
Another way of doing this is using regular expressions, science you can’t insert HTML tags to a text node.
First I am using a regular expressions to catch parts of the body.innerHTML property that are outside of the HTML tags.
But, the string contains also another data, and if I will directly replace it with thge new data some text will be lost.
Insted, I get each match as an argument for a function, and inside this function I use another regular expression.
Notice that you have to replace «foo» twice.
How to replace entire HTML content with Javascript?
I tried to use $(«html»).html(this.responseText); . Which replaces the content but it does not replace the head and body tags. So for example if i want replace this content:
This is a Heading
This is a Heading
And it messed my css so. I have tried without scripts, and it worked fine. What is the solution for this problem? I have also tried with javascript approach
document.open(); document.write(this.responseText); document.close();
But it confuses my javascripts. I am getting redeclaration syntax error. My real code where i want to implement: