Home >Web Front-end >JS Tutorial >Simple analysis of javascript replace() method_javascript skills

Simple analysis of javascript replace() method_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:58:081101browse

The simplest ability of replace() is simple character replacement. The sample code is as follows:

I think you can see the result after running it, it only replaces the first letter. But if you add a regular expression, the result will be different! Haha, that's right. replace() supports regular expressions, it can match characters or strings according to the rules of regular expressions, and then replace them!

 Haha, you must have discovered it. This still only replaces the first letter a. If you are familiar with regular rules, this will not be a problem for you. It's OK with a little modification.

You can also do this and see the effect!

The examples I give here are very simple applications. At this point, replace() 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 letters of all words.


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh it to execute
]

From the above, it can be seen that when the regular When the 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, the function of replace() to process strings has become unprecedentedly powerful!
Finally, let me give you an example. It is so simple to use replace() to reverse all the words in a string.

[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute ]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn