从逗号分隔的字符串javascript中删除空值(Remove empty values from comma separated string javascript)

编程入门 行业动态 更新时间:2024-10-28 02:25:08
逗号分隔的字符串javascript中删除空值(Remove empty values from comma separated string javascript)

如何从JavaScript / jQuery中的逗号分隔字符串中删除空值?

有简单的方法,还是我需要循环并手动删除它们?

有没有办法合并JavaScript / jQuery中的所有拆分(str和str1)?

码:

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

预期产量:

a,b

帮助将不胜感激:)

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 :)

最满意答案

在我看来,你要删除+ , "|" , "-"和字符串开头和结尾的空格,并希望用一个逗号替换字符串中的那些空格。 这是三个正则表达式:

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

(?:[\s+]|"[|-]")匹配空格或加号,或"|" 或"-" 。 最后的+重复一次或多次。 在第一个表达式中,我们将匹配锚定到字符串的开头并将其替换为空(即删除它)。 在第二个表达式中,我们将匹配锚定到字符串的末尾并将其删除。 而在第三个,没有锚,因为剩下的所有匹配必须在字符串内的某个地方 - 我们用,替换那些。 注意最后一个表达式的g修饰符 - 没有它只会替换第一个匹配。

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 (i.e. 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.

更多推荐

本文发布于:2023-08-07 19:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   字符串   Remove   javascript   empty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!