TheWebs
TheWebs

Reputation: 12923

Easiest way to replace some single quotes in javascript?

So I have the following example string: 'Sam's Place' and I want to change it to "Sam's Place". Is there an easy way to manipulate a sting with single quotes into using double quotes? The important part is to keep the one single quote in the string.

I have tried:

var samsPlaceName = samsPlace.replace(/'/g, '"');

// And:

JSON.stringify(samsPlace);

// Both give me:

'Sam"s Place'

'"Sam's Place"'

All I want is to change the string to be: "Sam's Place".

Can this be done?

Upvotes: 2

Views: 98

Answers (2)

akuiper
akuiper

Reputation: 214927

// assume you have a string
var samsPlace = "'Sam's Place'";
console.log(samsPlace);

// replace the single quote at the beginning and end of string with double quote by
// using anchors where ^ denotes BOS (beginning of string) and $ denotes EOS (end of 
// string)
console.log(samsPlace.replace(/^'|'$/g, '"'));

Upvotes: 6

SpaceNinjaApe
SpaceNinjaApe

Reputation: 312

Can't you use this?

var str = '"Sams place"'
while(str.indexOf('"') != -1){
  str = str.replace('"',"'");
}

I hope i don't get you wrong :S

Upvotes: -1

Related Questions