如何在 Javascript 中替换字符串中的撇号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11871289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:27:53  来源:igfitidea点击:

How to replace an apostrophe in a string in Javascript?

javascriptstring

提问by Kinnan Nawaz

Given a string in Javacript, such as

给定一个 Javacript 中的字符串,例如

var str = "this's kelly";

I want to replace the apostrophe (') with another character. Here is what I've tried so far:

我想用另一个字符替换撇号 (')。这是我迄今为止尝试过的:

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

None of these work.

这些都不起作用。

How do I do it?

我该怎么做?

Can you also please advices me with the invalid characters that when passed to the query string or URL crashes the page or produces undesired results ? e.g passing apostrophe (') produces undesired result are their any more of them.

您能否也建议我使用无效字符,这些字符在传递给查询字符串或 URL 时会导致页面崩溃或产生不想要的结果?例如,传递撇号 (') 会产生不希望的结果。

回答by jli

var str = "this's kelly"
str = str.replace(/'/g, 'A');

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

您的版本无法正常工作的原因是因为str.replace返回了新字符串,而没有进行适当的更新。

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

我还更新了它以使用 的正则表达式版本str.replace,当与g选项结合使用时,它会替换所有实例,而不仅仅是第一个。如果您真的希望它只是替换第一个,请删除g或执行str = str.replace("'", 'A');

回答by Prasanth

Do this:

做这个:

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

回答by TommyBs

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

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

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

您运行该函数但不再将其分配给任何东西,因此 var 保持不变