Record a mistake made in a development.
- Requirement: Use JS to replace some substrings in the string with the specified new string .
Implementation ideas: The impression of JS string substitution has a replace
method, the replace
method receives two parameters, the first is to replace the substring or regular matching pattern, the second parameter is a new string. I am not familiar with the regular, think that the use of strings to meet the needs.
Simple test
var str="apples are round";var newStr = str.replace(‘apples‘,‘oranges‘)//newStr 值为:oranges are round
The result of the operation is correct, wrong in the project, error reason: When replace
the first argument of the method is a string, only the first match is replaced.
Test again
var str1="apples are round, and apples are juicy.";var newStr1 = str1.replace(‘apples‘,‘oranges‘);//newStr1 值为:oranges are round, and apples are juicy.
- The result of the operation does not match the expectation, only one is replaced.
Workaround: You also need to use regular expressions: Regular expressions contain options for global substitution (g) and ignoring case (i).
var str2="apples are round, and apples are juicy.";var newStr2 = str2.replace(/apples/g,‘oranges‘);//newStr2 值为:oranges are round, and oranges are juicy.
JS string substitution (replace)