15

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'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.

4

3 回答 3

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

于 2012-08-08T18:59:40.803 回答
2

做这个:

str = str.replace("'","A");
于 2012-08-08T18:59:41.267 回答
2

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

您正在运行该功能,但没有再次将其分配给任何东西,因此 var 保持不变

于 2012-08-08T19:00:42.583 回答