Why doesn't the javascript replace global flag work in Chrome or IE, and how to I work around it?

前端 未结 3 560
栀梦
栀梦 2021-01-01 16:57

According to the String.prototype.replace() page on MDN, I should be able to easily replace multiple patterns just by using

str.replace(\'what to replace\',          


        
3条回答
  •  耶瑟儿~
    2021-01-01 17:41

    The very page you linked to mentions:

    The use of the flags parameter in the String.replace method is non-standard. For cross-browser compatibility, use a RegExp object with corresponding flags.

    Basically, it should only work on Firefox. As per the documentation, you can generate regexes dynamically using new RegExp:

    var regex = new RegExp(variable, 'gi');
    questionText = questionText.replace(regex, rep);
    

    This will need variable to be escaped, however.

提交回复
热议问题