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.
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.
As such, if you know that you need to include an apostrophe within a string, then enclose the string with quotation marks.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With