0

I am having an object with userGuid as property. The userGuid property has Guid value enclosed in double quotes.

I have used replace() method, but it is replacing first occurrence of a character only. Therefore, I have used replace() method twice to remove both quotations, like below:

var UserID = criteria.userGuid.replace('"', '').replace('"', '');

Can anyone suggest the best way to replace single character in a variable?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Shankar
  • 256
  • 2
  • 12
  • As this question was closed as duplicate, I really don't care here, but for future reference it is SO etiquette to accept the *earliest* answer when several identical solutions are provided around the same time. Cheers – iCollect.it Ltd Jul 17 '15 at 16:46
  • Ok, next time, I will type "give meeeeeeeeeeeeeeeeeeee 5 secs", and will be still the first even if I edit my answer with really useful information in half an hour. – Wiktor Stribiżew Jul 17 '15 at 20:17

2 Answers2

2

Use replace with a RegEx literal instead and the "g" global option

e.g.

var UserID = criteria.userGuid.replace(/"/g, '');

Reference: http://www.w3schools.com/jsref/jsref_regexp_g.asp

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
1

You need to use a regex in the replace function with g modifier:

var UserID = criteria.userGuid.replace(/"/g, '');

var userGuid = "122343\"EE43\"45\"FG";
var UserID = userGuid.replace(/"/g, '');
document.write(UserID);

From replace() reference at MDN:

To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • You are determined to get this one (even though you came in 6 seconds later) :) – iCollect.it Ltd Jul 17 '15 at 11:54
  • I did not see your answer in my browser. Also, you made a typo in your answer at the very beginning. And did not provide code itself. Then you added the line I already had in my answer. No. Either sportsmanship, or a duplicate. – Wiktor Stribiżew Jul 17 '15 at 11:54
  • Just to clarify, I stated the correct answer quite clearly in English (minus a single character typo) before you posted *and* there is only one possible way to code that description. If it was not for the fact that you were *only* 6 seconds later than me, it would look like *you copied me*. :P – iCollect.it Ltd Jul 17 '15 at 13:21