How to separate a string by commas, except when you have a space later

Asked

Viewed 796 times

6

I have a string and I need to separate it into one array. However, the separator character needs to be the comma (,), but if you have a space right after ("") she is preserved in separation.

I’m trying to do this with split, but I’m not getting it. Example of what I want:

string = "1,0,true,Yes, please"; 

I need to:

array = ["1","0","true","Yes, please"] 
  • I don’t understand what you mean by "the ',' needs to be preserved"

  • @Jrd I believe it is the comma needs to be preserved

2 answers

5


You can use the following regular expression to make the division:

/,(?! )/

Being:

  • , selects all the commas;
  • (?! ) one Lookahead negative which ensures that there can be no spaces after the comma.

That way, you can do it like this:

const string = '1,0,true,Yes, please'
const splittedString = string.split(/,(?! )/)

console.log(splittedString)

  • 1

    If I’m not mistaken, in split no need to put the flag g, by default it separates the entire string...

  • 1

    That’s true! Thanks for the remark... I just tested it here on the console and it really doesn’t matter. I edited the answer. ;)

  • Thank you very much!

  • Suggestion, trade space for \s, this meta-character is used for different types of spacing, such as space, tab, breaks, etc.

0

Will it always be in this format? If yes you can use this code:

var string = "1,0,true,yes, please";
var array = [];
var preservado = string.substr(string.indexOf(", ") - 3);
array = string.substr(0, string.indexOf(', ') -4).split(',');
array.push(preservado);
console.log(array);     

If by chance it changes, you can add if statements to suit your need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.