我想" "
在删除时按空格分割,","
在保留时也用逗号分割。
var str = "This is a word, and another."
var regexKeepCommaDelimeter = new RegExp(/(,)/,'g')
var regexKeepCommaRemoveSpace = new RegExp(/(????)/,'g')
var splitArray = str.split(regexKeepCommaRemoveSpace)
var desiredArray = ['This', 'is', 'a', 'word', ',', 'and', 'another.' ]
var testPassed = splitArray.every((x,i)=> x == desiredArray[i])
console.log('Arrays match:', testPassed)
匹配空格,并使用分割时匹配并捕获逗号str.split(/\s+|(,)/).filter(Boolean)
。
或者,您可以匹配除空格和逗号以外的任意数量的字符,或者仅与匹配一个字符str.match(/[^\s,]+|,/g)
。
var str = "This is a word, and another.";
console.log(
str.split(/\s+|(,)/).filter(Boolean)
);
// => ["This", "is", "a", "word", ",", "and", "another."]
console.log(
str.match(/[^\s,]+|,/g)
);
// => ["This", "is", "a", "word", ",", "and", "another."]
该.filter(Boolean)
部分将从结果数组中删除由于最终连续匹配或字符串开头的匹配而出现的空项目。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句