JS code for replacing plus sign

I am having a problem for quite a while now - I need to replace plus sign “+” in a string.
I am using two variants like shown here

but they both are not working. What makes me furious is that I just cannot debug the problem - it is just not replacing silently, no errors jumping out… What am I doing wrong?

Welcome to the forums @bizpages!

Simple example to get you started but look at the docs for more info:

test = "hello"
test = test.replace("hello", "goodbye")
//output: goodbye

MDN should be your go-to for JS documentation.

It matches the documentation- so try running your code on something other than Codecademy.


Thanks. But the code
test = "hello" test = test.replace("hello", "goodbye") console.log(test) //output: goodbye
will only replace once and then exit? For replacing all instances you need a /g flag right? And you cannot put the flag after “hello”, right? You will need something like /+/g like in my example. And my examples are not working…

storyWords = storyWords.replace(/really/g, 'pizza')

You can try /word/gi to replace all cases. For example, the code above will only work if the word is really, but what if it is really. with a period at the end?

storyWords = storyWords.replace(/really/gi, 'pizza')
1 Like

If you scroll to the bottom of the docs link there’s info for replaceAll() but that’s not fully implemented yet.

For differing flavors of regex look at this thread in stackoverflow https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string

Unless you’re trying to do a split… can you post your code so we can see the context a little better?

Yes. Here is the code:

	1) val=val.replace(/\+/g, '_my_plus_');
	2) val=val.replace(/+/g, '_my_plus_');
What I am trying to say is that for PLUS SIGN "+", the regexp does not work. It works OK for other non-alphabet characters, such as minus "-" for example.

Number 1 works perfectly for me in the console (I tested some strings that have a “+” char in them). Is there some other context it’s around, maybe something else in your code is throwing it off, that’s why I ask.

I found a way that works for me:
val=val.replace(/[+]/g, ‘my_plus’);

1 Like