How to replace an apostrophe in a string in Javascript?

前端 未结 3 1902
没有蜡笔的小新
没有蜡笔的小新 2021-02-07 19:43

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:13

    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');

提交回复
热议问题