In JavaScript, the string's function, replace () is simply too much to love. It is a flexible and powerful character replacement processing power, so I can not help but want to introduce it to you.
Replace () The simplest is the ability to be a simple character replacement. The sample code is as follows:
<script language="javascript">
var strM = "javascript is a good script language";
//在此我想将字母a替换成字母A
alert(strM.replace("a","A"));
</script>
I think we can see the result when we run it, it only replaces the first letter. But if you add regular expressions, the results are different! Oh, yes. Replace () supports regular expressions, which match characters or strings according to the rules of regular expressions, and then give replacements!
<script language="javascript">
var strM = "javascript is a good script language";
//在此我想将字母a替换成字母A
alert(strM.replace(/a/,"A"));
</script>
Oh, you must have found out. This only replaces the first letter A. If you are familiar with the regular, then this will be difficult for you. Just a little change is OK.
<script language="javascript">
var strM = "javascript is a good script language";
//在此将字母a全部替换成字母A
alert(strM.replace(/a/g,"A"));
</script>
You can also do this, see the effect!
<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 have here are simple applications where replace () is proportional to your ability to use regular expressions at this point. Your regular expression is stronger, hehe, then you will be madly in love with it.
Of course, the reason I recommend replace () is not because it works with regular expressions, but because it can work with functions to play a powerful role.
Let's take a look at a simple example: capitalize all the first letters of the word.
<script language="java script">
var strM = "java script 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 is clear from the above that when a regular expression has a "G" flag, the representative will handle the entire string, that is, the transformation of the function change will be applied to all matching objects. The function has three or more parameters, depending on the regular expression.
With functions and regular expressions, the replace () processing string has an unprecedented power!
Finally, for example, it is so easy to reverse all the words in a string, using the replace () process.
<script language="java script">
var strM = "java script 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>