【发布时间】:2021-12-25 00:29:50
【问题描述】:
我有一个这样的字符串:
"|hello| + |world| / |again|"
我需要获取| 中的子字符串并返回一个这样的数组:
["hello", "world", "again"]
实现这一目标的最佳方法是什么?
【问题讨论】:
-
可能正则表达式是一个很好的方法
标签: javascript arrays string algorithm
我有一个这样的字符串:
"|hello| + |world| / |again|"
我需要获取| 中的子字符串并返回一个这样的数组:
["hello", "world", "again"]
实现这一目标的最佳方法是什么?
【问题讨论】:
标签: javascript arrays string algorithm
array = [];
let name = "";
let input = "|hello| + |world| / |again|";
let index = 0;
let isStart = false;
while (index < input.length) {
if (input[index] == '|') {
isStart = !isStart;
if (!isStart) {
array.push(name);
name = "";
}
} else {
if (isStart) {
name = name + input[index];
}
}
index++;
}
console.log(array);
【讨论】:
您可以使用正则表达式在管道 (/|) 之间搜索仅由字母 (([A-Za-z])) 组成的组,其中管道将从实际匹配中省略(用 (?:) 包裹)- 然后使用 @ 987654321@ 获取所有匹配项,.map 仅获取捕获组的结果(省略非捕获)- 见下文:
const str = "|hello| + |world| / |again|";
const re = /(?:\|)([A-Za-z]+)(?:\|)/g;
const results = [...str.matchAll(re)].map((entry) => entry[1]);
console.log(results);
这将仅匹配管道之间的那些单词。如果您的字符串中有其他单词 not 包裹在管道之间,它们将被忽略。像下面的sn-p:
const str = "|hello| + |world| / |again| how are |you| doing?";
const re = /(?:\|)([A-Za-z]+)(?:\|)/g;
const results = [...str.matchAll(re)].map((entry) => entry[1]);
console.log(results);
【讨论】:
如果该字符串不更改格式,请针对多个小写字母使用 a regular expression 到 match。
const str = '|hello| + |world| / |again|';
const regex = /[a-z]+/g;
console.log(str.match(regex));
【讨论】: