user760658
user760658

Reputation: 265

how to replace + in javascript?

How to replace character '+' in string with unicode?

E.G.
  Before replace -> "table+end"
  After replace -> "table002Bend"

I tried using

  tableName.replace(/+/g,"002B);

but browser running the JS is throwing the error stating:

Invalid identifier

Upvotes: 2

Views: 116

Answers (3)

newfurniturey
newfurniturey

Reputation: 38436

Using regex, the + has a special meaning in regex and needs to be escaped:

tableName = tableName.replace(/\+/g, '002B');

If you're just replacing a single +, you don't need regex:

tableName = tableName.replace('+', '002B');

However, the caveat with this is that it will only replace the first + encountered. A workaround to do a "quick" replace-all is to combine split() and join():

tableName = tableName.split('+').join('002B');

Upvotes: 1

Michal Klouda
Michal Klouda

Reputation: 14521

You need to escape +, if you use it in regex. Try it this way:

tableName.replace(/\+/g,"002B")

Unescaped plus sign is the match-one-or-more quantifier.

Note that you don't even need regex for this simple replace.

Upvotes: 3

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

Two things: the + character has a special meaning in regular expressions, if you look at the error you get:

SyntaxError: Invalid regular expression: /+/: Nothing to repeat

You see that + effectively means: repeat the previous "part" of the expression. You can use a backslash, to specify that you want to replace the literal + char (/\+/) or you can create a character class, wherein you don't need to escape all special chars: /[+]/.

After that, you might still have an error shown because of a missing string delimiter:

tableName.replace(/+/g,"002B);//<--missing closing "

All in all, either one of these should do the trick:

tableName.replace(/\+/g,"002B");
tableName.replace(/[+]/g,"002B");

If, however you want to "url-encode" a string, why not simply use encodeURI(tableName)?

Upvotes: 2

Related Questions