I'm making an extension for google chrome and i would like to be able find certain pieces of text and replace them with random letters or numbers using javascript except the certain text is a variable entered by the user for example they enter the word dog and all words that say dog are found and replaced as explained before . HELP greatly wanted
-
1Where do you plan to search for the "_certain pieces of text_"? The entire page? In certain form elements? You need to make your question more specific. Please include examples. – jahroy Jan 05 '13 at 01:01
-
1What have you tried? Did you try entering 'javascript replace text' in any search engine? – Stuart Jan 05 '13 at 01:44
2 Answers
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.

- 1
- 1

- 5,509
- 8
- 45
- 71
The String object has lots of useful methods.
var theNewString = theString.replace(findThis, replaceWithThis);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
// Generates a string of random letters
function generateRandomKey(number) {
var key = String();
var values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(var i = 0; i < number; i++) {
key += values.charAt(Math.floor(Math.random() * values.length));
}
return key;
}