How to replace an apostrophe in a string in Javascript?

前端 未结 3 641
死守一世寂寞
死守一世寂寞 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: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');

提交回复
热议问题