简体   繁体   中英

Remove empty values from comma separated string javascript

How do I remove empty values from an comma separated string in JavaScript/jQuery?

Is there a straightforward way, or do I need to loop through it and remove them manually?

Is there a way to merge all the splits (str and str1) in JavaScript/jQuery?

CODE:

var str = '+ a + "|" + b';
var str1 = '+ a + "-" + b';

str = str.split("+").join(",").split('"|"').join(",");
str1 = str1.split("+").join(",").split('"-"').join(",");
console.log(str); //, a , , , b
console.log(str1); //, a , , , b

EXPECTED OUTPUT :

a,b

Help would be appreciated :)

As I see it, you want to remove + , "|" , "-" and whitespace from the beginning and end of the string, and want to replace those within the string with a single comma. Here's three regexes to do that:

str = str.replace(/^(?:[\s+]|"[|-]")+/, '')
         .replace(/(?:[\s+]|"[|-]")+$/, '')
         .replace(/(?:[\s+]|"[|-]")+/g, ',');

The (?:[\\s+]|"[|-]") matches whitespace or pluses, or "|" or "-" . The + at the end repeats it one or more times. In the first expression we anchor the match to the beginning of the string and replace it with nothing (ie remove it). In the second expression we anchor the match to the end of the string and remove it. And in the third, there is no anchor, because all matches that are left have to be somewhere inside the string - and we replace those with , . Note the g modifier for the last expression - without it only the first match would be replaced.

The other answer is useful, and may be exactly what you are looking for.

If, for some reason, you still want to use split , luckily that method takes a regex as separator, too:

str = str.split(/\s*\+\s*(?:"\|"\s*\+\s*)?/).slice(1).join(",");

str1 = str1.split(/\s*\+\s*(?:"-"\s*\+\s*)?/).slice(1).join(",");

Because you have a plus sign in front of the "a", you can slice the array to return only the elements after it.

Also, since you mentioned you were new to regular expressions, here is the explanation:

  • any amount of space
  • a plus sign
  • any amount of space
  • optional (because of the ? after the group, which is the parentheses): a non-capturing (that is what the ?: means) group containing:
    • "|"
    • any amount of space
    • another plus sign
    • any amount of space

工作完全正常:str.split(/ [,] + /)。filter(function(v){return v!==''})。join(',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM