繁体   English   中英

根据单词拆分字符串并使用 `^` 符号突出显示部分

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM