Home >Web Front-end >JS Tutorial >JS uses the replace() method and regular expressions to search and replace strings_javascript skills
1. Replacement of JS strings and use of replace() method
The replace(regexp,replacement) method has two parameters. The first parameter can be a plain text string or a RegExp object. For details, please see the use of RegExp objects; the second parameter can be a string or a RegExp object. a function.
The following is an example of JS string replacement:
Example 1:
2. Use of RegExp object
JavaScript provides a RegExp object to complete operations and functions related to regular expressions. Each regular expression pattern corresponds to a RegExp instance. There are two ways to create instances of RegExp objects.
Use the explicit constructor of RegExp, the syntax is: new RegExp("pattern"[,"flags"]); use the implicit constructor of RegExp, in plain text format: /pattern/[flags]. The two statements in Example 4 are equivalent.
Example 4:
The exec() method returns an array, which stores the matching results. If no match is found, the return value is null.
Example 5:
RegExpObject.test(string)
Returns true if the string string contains text matching RegExpObject, otherwise returns false.
Example 6: