0

I wanted to convert strings into array by removing "+" characters. It is getting converted only for 1st element and not for all. Help me to convert "+" as "," for all the elements.

let myString = 'jan + feb + mar + april ';

let change = myString.replace("+",",");
console.log(change);

let myArray = change.split(",");
console.log(myArray);

OUTPUT:

jan , feb + mar + april

Array [ "jan ", " feb + mar + april " ]

I also tried using below option it raised an error

let myString = 'jan + feb + mar + april ';

let change = myString.replace(/+/g,",");
console.log(change);

OUTPUT

SyntaxError: nothing to repeat

Community
  • 1
  • 1
user9151444
  • 31
  • 1
  • 9
  • Does this answer your question? [How to replace all dots in a string using JavaScript](https://stackoverflow.com/questions/2390789/how-to-replace-all-dots-in-a-string-using-javascript) – blaz Mar 08 '20 at 15:05

1 Answers1

3

Just split on the characters you have.

let myArray = myString.split(" + ");

There's no need to do a substitution first.

(That said, + is a special character in a regular expression so you need to escape it with \ if you did want to keep your current approach).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335