HTML JS REPLACE

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?

Читайте также:  Диплом mysql php html

@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

Читайте также:  Php check if folder exists

Источник

Replace text in a website

I’m looking to replace text in a webpage (any webpage I want to run it on) using JavaScript. I’m not an expert in JavaScript, so I am sort of lost. If I can help it I would like to avoid jQuery. Through Google, I’ve found this stackoverflow question. But when I inject document.body.innerHTML = document.body.innerHTML.replace(‘hello’, ‘hi’); into a webpage it sort of messes the page up. It seems to make the page revert to basic text and formatting. Also, I’m wondering if the regex code from here, could be used. Again, I really am not sure how to use it. What it would do is replace only webpage text — not links or filenames. I’m using Google Chrome incase that matters.

If you perform a string replace on innerHTML it will regenerate all elements and lose event bindings.

What do you mean by «any webpage I want to run it on»? Do you have access to the code of all of these sites? Or do you want to do the replacement on sites like cnn.com, too?

Oh, that is just an example. I would really just like to be able to automatically screen certain text. 😀

2 Answers 2

You could perform your repleacements on all the just the text nodes in the DOM:

function replaceTextOnPage(from, to)< getAllTextNodes().forEach(function(node)< node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'), to); >); function getAllTextNodes()< var result = []; (function scanSubTree(node)< if(node.childNodes.length) for(var i = 0; i < node.childNodes.length; i++) scanSubTree(node.childNodes[i]); else if(node.nodeType == Node.TEXT_NODE) result.push(node); >)(document); return result; > function quote(str)< return (str+'').replace(/([.?*+^$[\]\\()<>|-])/g, "\\$1"); > > 
replaceTextOnPage('hello', 'hi'); 

Note that you will need to SHIM forEach in older browsers or replace that code with a loop like so:

var nodes = getAllTextNodes(); for(var i = 0; i

I’ve been trying to implement this in a Chrome Extension, but it only replaces some of the matches. Any more help? (My Chrome is the newest version.)

@Numeri If the phrase occurs more than once in the same text node, you’ll need to either keep calling replace until it does nothing or use a RegExp with the global flag. I updated my answer to show how to do it using a RegExp.

Читайте также:  Javascript value в переменных

Recently, I had to exercise a similar problem, and I came up with something similar to this:

       
Some text that includes both hello and hi. And a hello.

The result will be that you will get a page saying this:

Some text that includes both hi and hi. And a hi.

while the original source still says:

Some text that includes both hello and hi. And a hello.

The tricky bits are really just a few — first, you want the window.onload trigger to be included at the bottom of body, so the DOM loads fully before running any JS on it. Second, you must have a top-level block element that you assign a unique ID which you can reference from JS. Third, the convert function uses a regular expression, which executes a global case-insensitive replace of the string «hello» by changing it to «hi».

Your specific application may require to instead capture all of the occurences and then parse them in a loop, which may (or may not) cause some performance issues. Be careful 🙂

Источник

How to replace text in html document without affecting the markup?

How can I write a javascript/jquery function that replaces text in the html document without affecting the markup, only the text content? For instance if I want to replace the word «style» with «no style» here:

 This TD has style This TD has style too  

I don’t want the replacement to affect the markup, just the text content that is visible to the user.

2 Answers 2

You will have to look for the text nodes on your document, I use a recursive function like this:

function replaceText(oldText, newText, node) < node = node || document.body; // base node var childs = node.childNodes, i = 0; while(node = childs[i])< if (node.nodeType == 3)< // text node found, do the replacement if (node.textContent) < node.textContent = node.textContent.replace(oldText, newText); >else < // support to IE node.nodeValue = node.nodeValue.replace(oldText, newText); >> else < // not a text mode, look forward replaceText(oldText, newText, node); >i++; > > 

If you do it in that way, your markup and event handlers will remain intact.

Edit: Changed code to support IE, since the textnodes on IE don’t have a textContent property, in IE you should use the nodeValue property and it also doesn’t implements the Node interface.

Watch out for 2011 builds of MSIE9 — they have node.textContent support, but if you try and assign a new value using node.textContent = . then those builds crash the entire browser with A problem with this website caused Internet Explorer to close. Later builds (2012) seem OK. The workaround is to assign with node.nodeValue = . inside the if (node.textContent) part of the loop regardless and just forget doing it with textContent.

Источник

Оцените статью