0

How do I replace ' in javascript. For example I want to convert O'conor to O-conor. This doesnt work. I am doing something stupid.

var dummyStr =  "O'conor";
dummyStr.replace("'","-");
console.log(dummyStr); //prints O'conor 
dummyStr.replace(/'/g,"-"); //still prints O'conor not O-conor

Please mark duplicate if this has already been asked elsewhere.

3

4 Answers 4

7

replace (cf. replace on W3Schools) does not modify the current string. You have to assign it like this :

dummyStr = dummyStr.replace("'","-");
console.log(dummyStr); //prints O-conor
Sign up to request clarification or add additional context in comments.

2 Comments

i feel like a moron! Thanks
No worry, that's a common issue :-)
3

You need to assign a variable to the return value of replace()

e.g.

var dummyStr =  "O'conor";
var ammendedString = dummyStr.replace("'","-");
console.log(ammendedString ); 

2 Comments

feel like a moron! Thanks
No problems, it's easy to miss things like that, at a more fundamental level, try to remember that strings in JavaScript are immutable, so you can't 'change' them as such, you generally need to run functions against them and either assign the result to something else, or back to the original variable.
3

you just need to store this to some variable after replace, like below

dummyStr = dummyStr.replace("'","-");

Comments

3
dummyStr = dummyStr.replace("'","-");

Btw for replacing all: Replace All - StackOverFlow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.