var str = "<img <img <img"; var res = str.replace("img", "img class='img-responsive'"); alert(res) 

Why is only 1 <img replaced here

2 answers 2

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"); 
  • one
    still forgot the regulars version /img/g - Grundy

The 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 not null or undefined .

  1. If searchValue is not undefined and not null , then
    1. Let replacer be the @@ replace method in searchValue .
    2. If replacer is not undefined , then the argument is a regular expression
      1. Return the result of applying replacer
  2. Let string be this cast to string.
  3. Let searchString be the searchValue converted to a string.
  4. Let the functionalReplace be IsCallable(replaceValue) .
  5. If functionalReplace is false , then
    1. Let replaceValue be ToString(replaceValue) .
  6. 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 .
  7. If functionalReplace is true , then
    1. Let replValue be a Call(replaceValue, undefined,«matched, pos, and string») .
    2. Let replStr - ToString(replValue) .
  8. Otherwise
    1. Let captures be an empty list.
    2. Let replStr be GetSubstitution GetSubstitution(matched, string, pos, captures, replaceValue) .
  9. Let tailPos be pos + количество символов в совпадении .
  10. 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.
  11. 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.