我输入的内容可能类似于以下任何内容:
const str = 'key=value' // expected: str[0] == 'key', str[1] == 'value'
const str = 'key==value' // expected: str[0] == 'key', str[1] == 'value'
const str = 'key=value1=value2=value3' // expected: str[0] == 'key', str[1] == 'value1=value2=value3'
const str = 'key==value1=value2' // expected: str[0] == 'key', str[1] == 'value1=value2'
我有兴趣按键值对进行拆分,首先出现=
或==
并进行拆分。我尝试过:
var str = "this==that=these";
var spl = str.split(/==|=(.+)/); // spl[0] == 'this', spl[1] == 'undefined'
var spl = str.split(/=|==(.+)/); // spl[0] == 'this', spl[1] == 'undefined'
var spl = str.split(/[==]|[=](.+)/); // spl[0] == 'this', spl[1] == 'undefined'
但是这些没有用。有什么办法可以将其作为单行正则表达式?
答案 0 :(得分:1)
如果您使用split,则不想在RegEx中捕获实际的键或值,否则它们将成为被切除的子字符串的一部分。您只需要做str.split(/={1,2}/)
(与str.split(/==|=/)
相同)