JS string substitution (replace)

Source: Internet
Author: User

Record a mistake made in a development.

    1. Requirement: Use JS to replace some substrings in the string with the specified new string .
    2. 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
    3. 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.
    4. The result of the operation does not match the expectation, only one is replaced.
    5. 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.