Definition and usage
The replace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
[Ctrl+A to select all Note: If you need to introduce external Js, you need to refresh before executing]
[Ctrl+A to select all Note: If you need to introduce external Js, you need to refresh before executing]
But the result remains unchanged. If you are familiar with regular expressions, this will not trouble you. It's OK with a little modification.
Copy the code code as follows:
<script language="javascript">
var strM = "javascript is a good script language";
//Replace all letters a with letter A here
alert(strM.replace(/a/g,"A"));
</script>
You can also do this and see the effect!
Copy the code code as follows:
<script language="javascript">
var strM = "javascript is a good script language";
alert(strM.replace(/(javascript)/s*(is)/g,"$1 $2 fun. it $2"));
</script>
The examples I've given here are very simple applications, and replace() at this point is directly proportional to your ability to use regular expressions. The stronger your regular expression is, haha, the crazier you will fall in love with it.
Of course, the reason why I recommend replace() here is not because it can cooperate with regular expressions, but because it can also cooperate with functions and exert powerful functions.
Let’s look at a simple example first: capitalize the first letter of all words.
Copy the code code as follows:
<script language="javascript">
var strM = "javascript is a good script language";
function change(word)
{
return word.indexOf(0).toUpperCase()+word.substring(1);
}
alert(strM.replace(//b/w+/b/g,change));
</script>
It can be seen from the above that when the regular expression has the "g" flag, it means that the entire string will be processed, that is, the transformation of the change function will be applied to all matching objects. This function has three or more parameters, and the specific number depends on the regular expression.
With the cooperation of functions and regular expressions, replace()'s function of processing strings has become more powerful than ever!
Finally, as an example, it is so simple to use replace() to reverse all the words in a string.
Copy the code code as follows:
<script language="javascript">
var strM = "javascript is a good script language";
function change(word)
{
var result = word.match(/(/w)/g);
if(result)
{
var str = "";
for (var i=result.length-1; i>=0; i--)
{
str += result;
} return str;
}
else
{
return "null";
}
}
alert(strM.replace(//b(/w)+/b/g,change));
</script>