Home >Web Front-end >JS Tutorial >What is the string replacement function in javascript
In javascript, the string replacement function is "replace()". replace() is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression. The syntax is "string.replace(searchvalue,newvalue)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, the string replacement function is "replace()".
replace() function is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
Syntax
string.replace(searchvalue,newvalue)
Parameter value
Description | |
---|---|
searchvalue | Required. A RegExp object that specifies the substring or pattern to be replaced.Note that if the value is a string, it is retrieved as a literal literal pattern rather than first being converted to a RegExp object. |
newvalue | Required. A string value. Specifies functions for replacing text or generating replacement text.
Description:
String string method replace() performs a search and replace operation. It will look for substrings in string that match regexp and then replace those substrings with replacement. If regexp has the global property g, then replace() will replace all matching substrings. Otherwise, it only replaces the first matching substring.Example:
Replace string directly:"javascript".replace("a","A"); //返回jAvascript,只替换第一个aReplace according to regular expression:
"javascript".replace(/a/,"A"); //返回jAvascript,也是只替换第一个a,但是如果给正则表达式加一个全局属性g,则可以替换所有a ,如"javascript".replace(/a/g,"A"),返回jAvAscript,全部替换。
Real exam example :
If there are multiple spaces in a string, and there are one or more spaces in each place, turn all the multiple spaces in each place into one space, as follows: Convert the string a space space b space c space space space def space space g (a b c def g) into (a b c def g). The code is as follows:var removeSpace = function(str){ return str.replace(/\s+/g," "); } var str = "a b c def g"; console.log(removeSpace(str)); //输出a b c def g[Recommended learning:
javascript advanced tutorial]
The above is the detailed content of What is the string replacement function in javascript. For more information, please follow other related articles on the PHP Chinese website!