This morning when I want to write code for my plugins I have run into this problem—>How to replace a sub string within a text with another sub string using javascript. Even though I end up not using that javascript method but I would like to show you how to do it anyway in this article.
Suppose we have a string ‘Hello World’ and we would like to replace the entire word ‘World’ within that string with ‘Dude’ and then assign the new string to a new variable, we will use the replace method to do the job for us.
<script>
var greet = "Hello World";
var greetDude = greet.replace("World", "Dude");
</script>
Suppose you would like to replace the sub string ‘him’ within a text with another sub string from the user input and then displaying the latest changes on the alert box, you can do it with below code.
<script>
var text = "You will replace 'him' with new word, "
+ "so go ahead and type any word into the prompt box now!";
window.alert("You will replace him with new word, "
+ "so go ahead and type any word into the prompt box now!");
var repText = window.prompt("Enter the word to replace him","");
window.alert(text.replace(/him/g, repText));
</script>
Do you also know that we can create a new RegExp object instance within the replace method like this?
new RegExp(pattern, flags);
For example if we want to create a new text string by replacing the old word ‘this’ with the new word ‘my’, then we can use the following code.
<script>
var oldText = "hello this world";
var newText = oldText.replace(new RegExp("this","g"),"my");
</script>
In the next example, we are going to use the inline function to replace every number ’1′ within a string with the word ‘one’. As you can see, the replacement function will accept the matched snippets as its parameter and replacing them with the word ‘one’, the whole string is then return and appears on the alert box.
<script>
function numberToWord(stringValue) {
function changeNumberToWord(match) {
return 'one';
}
return stringValue.replace(/1/g, changeNumberToWord);
}
window.alert(numberToWord('1 + 1'));
</script>
See my review in comp.lang.javascript, Message-IDs and . at Google Groups