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
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
Share Improve this question asked Jan 5, 2013 at 0:56 ObcureObcure 1,0014 gold badges12 silver badges24 bronze badges 2- 1 Where 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 Commented Jan 5, 2013 at 1:01
- 1 What have you tried? Did you try entering 'javascript replace text' in any search engine? – Stuart Commented Jan 5, 2013 at 1:44
2 Answers
Reset to default 3Try 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 mand, 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/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.
The String object has lots of useful methods.
var theNewString = theString.replace(findThis, replaceWithThis);
https://developer.mozilla/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;
}