How to replace an apostrophe in a string in Javascript?

前端 未结 3 642
死守一世寂寞
死守一世寂寞 2021-02-07 20:04

Given a string in Javacript, such as

var str = \"this\'s kelly\";

I want to replace the apostrophe (\') with another character. Here is what I\

相关标签:
3条回答
  • 2021-02-07 20:08

    Do this:

    str = str.replace("'","A");
    
    0 讨论(0)
  • 2021-02-07 20:23

    str = str.replace("'", "A");

    Your running the function but not assigning it to anything again so the var remains unchanged

    0 讨论(0)
  • 2021-02-07 20:29
    var str = "this's kelly"
    str = str.replace(/'/g, 'A');
    

    The reason your version wasn't working is because str.replace returns the new string, without updating in place.

    I've also updated it to use the regular expression version of str.replace, which when combined with the g option replaces all instances, not just the first. If you actually wanted it to just replace the first, either remove the g or do str = str.replace("'", 'A');

    0 讨论(0)
提交回复
热议问题