The JavaScript string provides a replace method. The replace method can take two arguments: the first argument can be a RegExp object or a string, and the second argument can be a string or a function. If the first argument is a string, only the first string is replaced. If you want to replace all strings, you must use regular expressions.
- A code
var str="hello world";
var str1=str.replace("o"."h");
console.log(str1);//hellh world
Copy the code
The first line defines a string variable and initializes it. The second line uses the replace method to replace the o in the string with h. From the result, string substitution can only replace the first string.
- Code 2
var str="hello world";
var str1=str.replace(/o/g."h");
console.log(str1);//hellh whrld
Copy the code
The above code uses a regular expression to pass the parameters, and the regular expression matches all strings and replaces them.
- Code 3
var str="hello world";
var str1=str.replace(/o/g.function(match,pos,orginText){
console.log(pos);
return "a";
});
console.log(str1);//hella warld
Copy the code
The first line of the above code defines the string variable and initializes it. The second line calls the replace method of the string, with the first argument being a pattern match and the second argument being a function. The function takes three arguments: the first argument is the string to be matched, the second argument is the position to be matched, and the third argument is the original string. You can manipulate strings inside functions. With the function as the second argument, you can do some complex substitutions, such as making different substitutions for different characters when matching multiple characters.
- Code four
var str="hello world";
var str1=str.replace(/[ol]/g.function(match,pos,orginText){
console.log(pos);
if(match=="o") {return "a";
}
else {
return "b"; }});console.log(str1);//hebba warbd
Copy the code
The code pattern above matches all characters O or L and operates in the function. Replace the character O with a and the character L with b