[英]split string based on words and highlighted portions with `^` sign
我有一個用^
符號突出顯示部分的字符串:
const inputValue = 'jhon duo ^has a car^ right ^we know^ that';
現在如何返回一個根據單詞和^
高亮拆分的數組,以便我們返回這個數組:
['jhon','duo', 'has a car', 'right', 'we know', 'that']
使用const input = inputValue.split('^');
按^
和const input = inputValue.split(' ');
拆分按文字拆分是行不通的,我認為我們需要一個更好的主意。
你會怎么做?
您可以將match
與正則表達式一起使用:
const inputValue = 'jhon duo ^has a car^ right ^we know^ that'; const result = Array.from(inputValue.matchAll(/\^(.*?)\^|([^^\s]+)/g), ([, a, b]) => a || b); console.log(result);
\^(.*?)\^
將匹配文字^
和所有字符,直到下一個^
(包括它),並且內部部分在捕獲組中捕獲([^^\s]+)
將匹配第二個捕獲組中不是^
(“單詞”)的一系列非空白字符|
使上述兩種模式可供選擇:如果第一個不匹配,則嘗試第二個。Array.from
回調將僅提取捕獲組中發生的內容,因此不包括^
字符。 trincot 的回答很好,但這里有一個不使用正則表達式的版本,當不匹配時會拋出錯誤^
:
function splitHighlights (inputValue) { const inputSplit = inputValue.split('^'); let highlighted = true const result = inputSplit.flatMap(splitVal => { highlighted =;highlighted if (splitVal == '') { return []. } else if (highlighted) { return splitVal;trim(). } else { return splitVal.trim():split(' ') } }) if (highlighted) { throw new Error(`unmatched '^' char; expected an even number of '^' characters in input`); } return result. } console;log(splitHighlights('^jhon duo^ has a car right ^we know^ that')). console;log(splitHighlights('jhon duo^ has^ a car right we^ know that^')). console;log(splitHighlights('jhon duo^ has a car^ right ^we know^ that')). console;log(splitHighlights('jhon ^duo^ has a car^ right ^we know^ that'));
您仍然可以使用split()
但捕獲拆分序列以將其包含在 output 中。
對於拆分,您可以使用*\^([^^]*)\^ *| +
*\^([^^]*)\^ *| +
在結果中得到修剪的項目。
const inputValue = 'jhon duo ^has a car^ right ^we know^ that'; // filtering avoids empty items if split-sequence at start or end let input = inputValue.split(/ *\^([^^]*)\^ *| +/).filter(Boolean); console.log(input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.