-1

I'm trying to do some basic string manipulation on a text variable in Javascript. I have a few lines of code that look like this:

var someVar = 'first+last@domain.com';
var cleanVar = someVar.replace('@','_').replace('+','_');

When I run this code in Chrome's Javascript console, the value of cleanVar is first_last_domain.com... which is as intended. When this code runs on the live page in the browser, the replace() always works for th @ character, but never for the +.

To debug this, I've tried swapping positions of the .replace('@','_') with .replace('+','_') and even breaking things out like this:

var someVar = 'first+last@domain.com';
var cleanVar = someVar.replace('@','_');
var cleanVar2 = cleanVar.replace('+','_');

Surely I'm missing something rudimentary here. I know the + combines strings in Javascript... but not when surrounded by quotes, right?

ps2goat
  • 8,067
  • 1
  • 35
  • 68
Sam
  • 2,152
  • 6
  • 31
  • 44
  • [How is that?](http://jsfiddle.net/737hp127/1/). Both log `first_last_domain.com` in the fiddle. You're logging a wrong variable? – Teemu Aug 17 '15 at 17:05
  • 1
    possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – ps2goat Aug 17 '15 at 17:12
  • you just be doing something wrong. the running code works as expected, just like the console runned code – Alex Aug 17 '15 at 17:15
  • 1
    Not a dup, OP says that a character is not replaced at all, though it's not reproducable with the provided code. – Teemu Aug 17 '15 at 17:20
  • the question obviously is not how to replace all occurences in a string, is it? not a dub – Alex Aug 17 '15 at 17:20
  • @Alex, It seems like the only way to have this happen-- we're still waiting on feedback. – ps2goat Aug 17 '15 at 17:21
  • Bleh. This is on a Drupal site using JS Injector. All of the JS is being preprocessed and aggregated into a single file. If I turn that off, this problem vanishes. There must be some other script that's interfereing. Keeping preprocessing on and using the regex method below works for now. – Sam Aug 17 '15 at 17:35

1 Answers1

-1

This regex method worked for me:

var cleanVar = someVar.replace(/[+@]/g,'_');

(posted by someone earlier and then removed)

As noted by a commenter, this will replace all instances of @ and +. Remove the g to target only the first @ or +.

Sam
  • 2,152
  • 6
  • 31
  • 44