Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace an apostrophe in a string in Javascript?

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.

like image 407
Kinnan Nawaz Avatar asked Aug 08 '12 18:08

Kinnan Nawaz


People also ask

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you put an apostrophe in a string?

As such, if you know that you need to include an apostrophe within a string, then enclose the string with quotation marks.

What does apostrophe mean in JavaScript?

theAnchorText = 'I\'m home'; The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.


1 Answers

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

like image 75
jli Avatar answered Sep 21 '22 12:09

jli