繁体   English   中英

用逗号分割字符串,但在 JavaScript 中没有转义

[英]Split string by comma, but not escaped in JavaScript

我编写了用逗号分割字符串的代码:

"Keyword,slug,description".split(',');

这会产生一个像["Keyword", "slug", "description"]这样的数组

这在一段时间内运行良好,直到有人在他们的描述中需要一个逗号。

我知道我可以用match替换split并使用正则表达式,但我能想出的唯一正则表达式涉及负向后视,如下所示:

"Keyword,slug,description".match(/(?<!\\),/);

不幸的是,JavaScript 不支持lookbehinds。

有没有其他方法可以做到?

所以使用匹配而不是拆分

"Keyword,slug,description".match(/([^,]+),([^,]+),(.*)/);

会导致

["Keyword,slug,description", "Keyword", "slug", "description"]

正则表达式还有其他的写法,就随便挑个快点。

这是一个不太好的方法,但一般原则可以派上用场:

"keyword,slug,foo\\,bar"
.replace( '\\,', '{COMMA}' )
.split(',')
.map(function(v){return v.replace('{COMMA}',',')})

如果您手动将字符串作为输入,那么您可以通过 HTML 实体对逗号进行转义。

var message = 'This is a message with some comma(,) and (,) ';
message = message.replaceAll(",", "&#x2c;");
var params = 'title=Confirm,message='+message+'position=middle';
showAlert(params);

现在常规 .split 方法将起作用

function showAlert(params) {
  params = params.split(","); 
  // ...
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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