0

I want to replace all + occurrences on this string:

agheuhfu3r3wogfjnsdnvv++3fefda+3zcvfsdf342rsdff3+fwef

with this character: *

What I wrote is that and it replaces only the first occurrence

var str = "agheuhfu3r3wogfjnsdnvv++3fefda+3zcvfsdf342rsdff3+fwef"; 
var res = str.replace('+', '*');

What's wrong with this code?

1
  • You can do this 2 ways: 1. str.replace(/\+/g, ''); 2. str.split('+').join(''); Commented Mar 8, 2017 at 14:17

2 Answers 2

1

Try using Regular expression:str.replace(/\+/g, '*') which replaces all the + symbols with * where g is global modifier.

var str = "agheuhfu3r3wogfjnsdnvv++3fefda+3zcvfsdf342rsdff3+fwef"; 
var res = str.replace(/\+/g, '*');
console.log(res);

Take a tour in regular expression from here MDN JS's Regular Expression

Sign up to request clarification or add additional context in comments.

Comments

1

replace() takes a regular expression pattern.

If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier

var res = str.replace(/\+/g, '*');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.