我有一個這樣的字串:
"|hello| |world| / |again|"
我需要獲取里面的子字串|并回傳一個這樣的陣列:
["hello", "world", "again"]
實作這一目標的最佳方法是什么?
uj5u.com熱心網友回復:
您可以使用正則運算式搜索僅由([A-Za-z])管道( ) 之間的字母 ( )組成的組,/|其中管道將從實際匹配中省略(用 包裹(?:))--然后用于.matchAll獲取所有匹配項和.map結果以獲取捕獲的組僅(省略非捕獲)——見下文:
const str = "|hello| |world| / |again|";
const re = /(?:\|)([A-Za-z] )(?:\|)/g;
const results = [...str.matchAll(re)].map((entry) => entry[1]);
console.log(results);
這將僅用于匹配管道之間的那些單詞。如果您的字串中有其他未包含在管道之間的單詞,它們將被忽略。像下面的片段:
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);
uj5u.com熱心網友回復:
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);
uj5u.com熱心網友回復:
如果該字串不更改格式,請使用正則運算式來match針對多個小寫字母。
const str = '|hello| |world| / |again|';
const regex = /[a-z] /g;
console.log(str.match(regex));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359142.html
標籤:javascript 数组 细绳 算法
上一篇:排序演算法以保持雙頭背靠背
