How do I replace single quotes with double quotes in JavaScript?

后端 未结 7 591
遥遥无期
遥遥无期 2021-02-01 02:10

The following code replaces only one single quote:

7条回答
  •  灰色年华
    2021-02-01 03:04

    replaceAll(search, replaceWith) replaces ALL occurrences of search with replaceWith.

    Then, make sure you have a string by wrapping one type of qoutes by different type:

     "a 'b' c".replaceAll("'", '"')
     // result: "a "b" c"
        
     "a 'b' c".replaceAll(`'`, `"`)
     // result: "a "b" c"
    

    More about replaceAll

    replaceAll (MDN): replaceAll(search, replaceWith)

    It's actually the same as using replace() with a global regex(*), merely replaceAll() is a bit more readable in my view.

    (*) Meaning it'll match all occurrences.


    Example 1 - search with a string

    const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.' 
       
    console.log(p.replaceAll('2020', '2021'));
    // Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
    

    Example 2 - search with regex

    const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'    
    const regex = /2020/gi
    
    
    console.log(p.replaceAll(regex, '2021'));
    // Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
    

    Important(!) if you choose regex:

    when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".


    You can also use a function as replaceWith

    In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string.

提交回复
热议问题