0

I have a string looking like: some+thing+-+More

How do i replace the + sign?

I have tried the following without success:

temps = "some+thing+-+More";
temps = temps.replace("/+" /g, "blank");
temps = temps.replace("+" /g, "blank");
temps = temps.replace(/+/g, "blank");
Dan Davies Brackett
10.1k2 gold badges36 silver badges55 bronze badges
asked Mar 27, 2012 at 21:40
2
  • 1
    A character set will do it: /[+]/g or you can just escape it: /\+/g. Commented Mar 27, 2012 at 21:41
  • 1
    Note that "/+" actually has a different meaning - namely just these two characters. The escape character in JavaScript is \. Commented Mar 27, 2012 at 21:43

4 Answers 4

8

You need to escape the plus sign with a backslash, like so:

var temps ="some+thing+-+More";
temps = temps.replace(/\+/g, "blank");
answered Mar 27, 2012 at 21:42
Sign up to request clarification or add additional context in comments.

Comments

0
"+ + + +".replace(/\+/g, "blank")

This results:

"blank blank blank blank"

You should use the escape char:

temps = temps.replace(/\+/g, "blank");
answered Mar 27, 2012 at 21:43

Comments

0
temps = temps.replace(/\+/g, "blank");

jsfiddle example

Balaswamy Vaddeman
8,6003 gold badges33 silver badges40 bronze badges
answered Mar 27, 2012 at 21:44

Comments

0

Thanks Jonathan.

I took a different approach: I figure out the Hex number for + sign was 2B So....

temps = temps = temps.replace(/\x2B/g, "blank"); 

also did the trick!

BenMorel
37.1k53 gold badges208 silver badges339 bronze badges
answered Mar 27, 2012 at 22:03

1 Comment

This is actually a really good technique for lots of other situations. \x for the hex value and \u for unicode. For the OP's case it is a bit overkill but most developers should be aware of this none the less.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.