如何获取在 Javascript 中拆分我的字符串的分隔符?
How to get the delimiters that split my string in Javascript?
假设我有如下字符串:
var str = "hello=world&universe";
我的正则表达式替换语句是这样的:
str.replace(/([&=])/g, ' ');
如何从上面的正则表达式替换语句中获取分隔我的字符串的分隔符?
我希望结果是这样的:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];
你可以分成一组,然后再分开。
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);
这是使用 String.matchAll
的一种方法
const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
但仅供参考。您发布的字符串看起来像 URL 搜索字符串。您可能想使用 URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?
假设我有如下字符串:
var str = "hello=world&universe";
我的正则表达式替换语句是这样的:
str.replace(/([&=])/g, ' ');
如何从上面的正则表达式替换语句中获取分隔我的字符串的分隔符?
我希望结果是这样的:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];
你可以分成一组,然后再分开。
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);
这是使用 String.matchAll
的一种方法const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
但仅供参考。您发布的字符串看起来像 URL 搜索字符串。您可能想使用 URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?