如何从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 , , , bEXPECTED OUTPUT :
a,bHelp 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.
更多推荐
发布评论