Why do i need to add /g when using string replace in Javascript?

后端 未结 5 1133
走了就别回头了
走了就别回头了 2021-01-31 02:53

Why is the \'/g\' required when using string replace in JavaScript?

e.g. var myString = myString.replace(/%0D%0A/g,\"
\");

5条回答
  •  无人共我
    2021-01-31 03:22

    The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.

    A list of useful modifiers:

    1. g - Global replace. Replace all instances of the matched string in the provided text.
    2. i - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
    3. m - Multi-line replace. The regular expression should be tested for matches over multiple lines.

    You can combine modifiers, such as g and i together, to get a global case insensitive search.

    Examples:

    //Replace the first lowercase t we find with X
    'This is sparta!'.replace(/t/,'X');
    //result: 'This is sparXa!'
    
    //Replace the first letter t (upper or lower) with X
    'This is sparta!'.replace(/t/i, 'X');
    //result: 'Xhis is sparta!'
    
    //Replace all the Ts in the text (upper or lower) with X
    'This is sparta!'.replace(/t/gi, 'X' );
    //result: 'Xhis is sparXa!'
    

    For more information see the JavaScript RegExp Object Reference at the w3schools.

提交回复
热议问题