Home  >  Article  >  Web Front-end  >  What is the string replacement function in javascript

What is the string replacement function in javascript

青灯夜游
青灯夜游Original
2021-04-25 18:59:115176browse

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)".

What is the string replacement function in javascript

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

##ParameterDescriptionRequired. A RegExp object that specifies the substring or pattern to be replaced. Required. A string value. Specifies functions for replacing text or generating replacement text.
searchvalue 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
Return value: a new string obtained by replacing the first match or all matches of regexp with replacement.

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,只替换第一个a

Replace 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!

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