如果使用JavaScript匹配双引号,则拆分字符串

时间:2018-09-06 07:57:00

标签: javascript regex string

var test = 'This is the text with "UserName" and "Password"';

使用正则表达式分割测试(字符串)

我这样尝试过test.match(/"[^"]*"|\S+/g); 它返回:[This,is,the,test,with,UserName,and,Password]

我不想拆分每个单词,

预期结果= ['This is the text with','"UserName"','and','"Password"']

2 个答案:

答案 0 :(得分:1)

\S+匹配除空格以外的任何1个以上的字符。如果将\S+替换为[^"]+,则可以修正表达式以使其符合您的需要:

var s = 'This is the text with "UserName" and "Password"';
console.log(s.match(/"[^"]*"|[^"]+/g));
// Or, trim each item, too:
console.log(s.match(/"[^"]*"|[^"]+/g).map(x => x.trim()));

如果您将"[^"]*"模式包装到捕获组中以强制split方法也输出捕获的文本,则似乎还可以使用 splitting 方法您稍后可能需要使用.filter(Boolean))删除空项目:

var s = 'This is the text with "UserName" and "Password"';
console.log(s.split(/\s*("[^"]*")\s*/).filter(Boolean));

请注意,\s*已添加到模式中,以删除双引号子字符串周围的空格。

答案 1 :(得分:-1)

只需使用split方法并传递您的正则表达式。验证码

var test = 'This is the text with "UserName" and "Password"';

var a = test.split(/"/ig)
console.log(a)

相关问题