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.

lonelymo
  • 3,972
  • 6
  • 28
  • 36
  • possible duplicate of [Why does the Javascript replace() function not do anything?](http://stackoverflow.com/questions/18647411/why-does-the-javascript-replace-function-not-do-anything) – Bergi Apr 15 '14 at 06:58
  • you are doing right but you have to save value of `dummyStr.replace("'","-");` in varible, you can do like this `dummyStr = dummyStr.replace("'","-");` – Himanshu Apr 15 '14 at 06:59
  • exact duplicate of https://stackoverflow.com/questions/1433212/replace-method-doesnt-work – Bergi May 21 '14 at 22:16

4 Answers4

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
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
3

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

dummyStr = dummyStr.replace("'","-");
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
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 ); 
dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
  • feel like a moron! Thanks – lonelymo Apr 15 '14 at 06:59
  • 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. – dougajmcdonald Apr 15 '14 at 07:03
3
dummyStr = dummyStr.replace("'","-");

Btw for replacing all: Replace All - StackOverFlow

Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99