var str = "<img <img <img"; var res = str.replace("img", "img class='img-responsive'"); alert(res)
Why is only 1 <img
replaced here
var str = "<img <img <img"; var res = str.replace("img", "img class='img-responsive'"); alert(res)
Why is only 1 <img
replaced here
Because there is no "g" flag. It should be so
var res = str.replace(new RegExp("img", "g"), "img class='img-responsive'");
Or so - it is better read, but in IE does not work:
var res = str.replace("img", "img class='img-responsive'", "g");
/img/g
- GrundyThe question why the specification can answer, which shows the algorithm of the function String.prototype.replace
String.prototype.replace (searchValue, replaceValue)
When the
replace
method is called with the arguments searchValue and replaceValue , the following steps are taken:Check that
this
notnull
orundefined
.
- If searchValue is not undefined and not null , then
- Let replacer be the @@ replace method in searchValue .
- If replacer is not undefined , then the argument is a regular expression
- Return the result of applying replacer
- Let string be
this
cast to string.- Let searchString be the searchValue converted to a string.
- Let the functionalReplace be
IsCallable(replaceValue)
.- If functionalReplace is false , then
- Let replaceValue be
ToString(replaceValue)
.- Search in string for the first occurrence of searchString and set pos to the index of the first matched character from string and set matched to the value of searchString . If nothing found, return string .
- If functionalReplace is true , then
- Let replValue be a
Call(replaceValue, undefined,«matched, pos, and string»)
.- Let replStr -
ToString(replValue)
.- Otherwise
- Let captures be an empty list.
- Let replStr be GetSubstitution
GetSubstitution(matched, string, pos, captures, replaceValue)
.- Let tailPos be
pos + количество символов в совпадении
.- Let newString be the string formed by combining the substring to pos , replStr , and the remaining substring starting with the tailPos index. If pos is 0, the first element of the union is an empty string.
- Return newString .
Important: The replace function is intentionally generic; It does not require
this
be just a string. Thus, it can be transferred to other types of objects for use as a method.
Source: https://ru.stackoverflow.com/questions/541264/
All Articles