[英]Split string by comma, but not escaped in JavaScript
I wrote code that splits a string by comma:我编写了用逗号分割字符串的代码:
"Keyword,slug,description".split(',');
Which results in an array like ["Keyword", "slug", "description"]
这会产生一个像["Keyword", "slug", "description"]
这样的数组
This worked fine for awhile, until someone needed a comma in their description.这在一段时间内运行良好,直到有人在他们的描述中需要一个逗号。
I know I can replace split
with match
and use a regular expression, but the only regular expression I can come up with involves a negative lookbehind, like this:我知道我可以用match
替换split
并使用正则表达式,但我能想出的唯一正则表达式涉及负向后视,如下所示:
"Keyword,slug,description".match(/(?<!\\),/);
Unfortunately JavaScript doesn't support lookbehinds.不幸的是,JavaScript 不支持lookbehinds。
Is there any other way to do it?有没有其他方法可以做到?
So use match instead of split所以使用匹配而不是拆分
"Keyword,slug,description".match(/([^,]+),([^,]+),(.*)/);
will result in会导致
["Keyword,slug,description", "Keyword", "slug", "description"]
There are other ways to write the regular expression, just picked something quick.正则表达式还有其他的写法,就随便挑个快点。
Here's a not-so-nice way, but the general principle can come in handy:这是一个不太好的方法,但一般原则可以派上用场:
"keyword,slug,foo\\,bar"
.replace( '\\,', '{COMMA}' )
.split(',')
.map(function(v){return v.replace('{COMMA}',',')})
If you manually give the string as the input, then you can escape the comma via HTML entity.如果您手动将字符串作为输入,那么您可以通过 HTML 实体对逗号进行转义。
var message = 'This is a message with some comma(,) and (,) ';
message = message.replaceAll(",", ",");
var params = 'title=Confirm,message='+message+'position=middle';
showAlert(params);
Now regular .split method will work现在常规 .split 方法将起作用
function showAlert(params) {
params = params.split(",");
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.