Javascript .replace command replace page text?
The .replace
method is a string operation, so it's not immediately simple to run the operation on HTML documents, which are composed of DOM Node objects.
Use TreeWalker API
The best way to go through every node in a DOM and replace text in it is to use the document.createTreeWalker method to create a TreeWalker object. This is a practice that is used in a number of Chrome extensions!
// create a TreeWalker of all text nodes
var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT),
// some temp references for performance
tmptxt,
tmpnode,
// compile the RE and cache the replace string, for performance
cakeRE = /cake/g,
replaceValue = "pie";
// iterate through all text nodes
while (allTextNodes.nextNode()) {
tmpnode = allTextNodes.currentNode;
tmptxt = tmpnode.nodeValue;
tmpnode.nodeValue = tmptxt.replace(cakeRE, replaceValue);
}
To replace parts of text with another element or to add an element in the middle of text, use DOM splitText
, createElement
, and insertBefore
methods, example.
See also how to replace multiple strings with multiple other strings.
Don't use innerHTML or innerText or jQuery .html()
// the innerHTML property of any DOM node is a string
document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')
- It's generally slower (especially on mobile devices).
- It effectively removes and replaces the entire DOM, which is not awesome and could have some side effects: it destroys all event listeners attached in JavaScript code (via addEventListener or .onxxxx properties) thus breaking the functionality partially/completely.
- This is, however, a common, quick, and very dirty way to do it.
How to replace text with another text in javascript on page load?
You are replacing the entire time
element by using .replaceWith
. Instead, you need to change the inner HTML of the time
tag:
$(document).ready(function() { $("time").html($("time").html().replace('June', 'Juin'));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><time datetime="07:05 13-06-2020" data-area="ab">13 June <span>07:05</span></time>
Replace words in the body text
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');
Using .replace to replace text with HTML?
If you use .html
instead of .text
it will work. Change this line:
$(this).text(text.replace(':trump:', image.outterHTML));
to this:
$(this).html(text.replace(':trump:', image));
Note: because image
is a string you don't need the .outerHTML
.
If the messageBody
has more than just text inside (it contains HTML) then you'll also want to change this line:
var text = $(this).text();
to this:
var text = $(this).html();
so the full code would be:
function wow() {
$('.messageBody').each(function() {
var text = $(this).html();
var image = '<img class="emote" src="trump.png">';
$(this).html(text.replace(':trump:', image));
});
}
setInterval(wow, 1000);
Javascript to find and replace text
Try using the .replace()
method of JavaScript.
Supposing you have a div like so for containing text: <div id="test">Original Text</div>
, use this JavaScript code:
var orignalstring = document.getElementById("test").innerHTML;
var newstring = orignalstring.replace("original","replaced");
document.getElementById("test").innerHTML = newstring;
Basically, this will identify the entire content of the whole div, then find certain text and replace those terms, like you asked. If you want to replace multiple strings in one command, try this: How to replace multiple strings with the .replace() Method?. This is a question I asked a few weeks back about .replace()
.
Also, try this JSFiddle: http://jsfiddle.net/tGMaN/
If you want the user to be able to define the text to replace and the replacement text, you can easily do this through text fields or a prompt box, and these values can be stored as variables which are called in the .replace()
method.
Find and replace specific text characters across a document with JS
How about this, replacing @
with $
:
$("body").children().each(function () {
$(this).html( $(this).html().replace(/@/g,"$") );
});
http://jsfiddle.net/maximua/jp96C/1/
How to replace all occurrences of a string in a HTML page using Javascript
You should walk the DOM, find text nodes, and replace the found text in each.
Here's a simple example. You can make walkText()
more generic by passing a callback that does the replacement.
function walkText(node) { if (node.nodeType == 3) { node.data = node.data.replace(/foo/g, "bar"); } if (node.nodeType == 1 && node.nodeName != "SCRIPT") { for (var i = 0; i < node.childNodes.length; i++) { walkText(node.childNodes[i]); } }}walkText(document.body);
foo <b>foo</b> foo
Replace text in a website
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");
}
}
Quote function borrowed from this answer.
Usage:
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 < nodes.length; i++){
nodes[i].nodeValue = nodes[i].nodeValue.replace(new RegExp(quote(from), 'g'), to);
}
Replacing Text in HTML with JavaScript
Simple regular expression to fix it:
document.body.innerHTML = document.body.innerHTML.replace(/target string/g, "replacement string");
How to change all texts in DOM without breaking existing HTML?
Iterate over all text nodes, and change their nodeValue
if they contain an a
:
function getAllTextNodes() { var walker = document.createTreeWalker( document.body, NodeFilter.SHOW_TEXT, null, false );
var node; var textNodes = [];
while(node = walker.nextNode()) { textNodes.push(node); } return textNodes;}
getAllTextNodes().forEach((node) => { const { nodeValue } = node; const newValue = nodeValue.replace(/a/g, 'x'); if (newValue !== nodeValue) { node.nodeValue = newValue; }});
<a href="/">abcd</a>
Related Topics
How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")
Why Does an Onclick Property Set with Setattribute Fail to Work in Ie
Firebase Query Methods Startat() Taking Case Sensitive Parameters
How to Use JavaScript or Jquery to Read a Pixel of an Image When User Clicks It
How to Remove Only the Parent Element and Not Its Child Elements in JavaScript
Getting "Typeerror: Failed to Fetch" When the Request Hasn't Actually Failed
JavaScript Functions Like "Var Foo = Function Bar() ..."
Destructuring a Default Export Object
Typeerror: _Firebase_Webpack_Imported_Module_2_.Default.Collection Is Not a Function
How to Add/Subtract Dates with JavaScript
How to Replace Captured Groups Only
Find Out How Long an Ajax Request Took to Complete
JavaScript to Sort Contents of Select Element
Normalizing Mousewheel Speed Across Browsers
Need to Cancel Click/Mouseup Events When Double-Click Event Detected
JavaScript If Statement with Multiple Permissible Conditions