Javascript 如何通过使用regex和split()函数,使用某种输入模式以数组的形式拆分段落。。?
我想搜索给定段落中的关键词,当输入关键词在该段落中遇到时,以数组的形式拆分该段落。搜索应采用不区分大小写的形式Javascript 如何通过使用regex和split()函数,使用某种输入模式以数组的形式拆分段落。。?,javascript,arrays,regex,search,Javascript,Arrays,Regex,Search,我想搜索给定段落中的关键词,当输入关键词在该段落中遇到时,以数组的形式拆分该段落。搜索应采用不区分大小写的形式 toFindString = "Stable NDA product"; paragraph = "NDA sampled and analyzed your “Sandhills Select Horse Feed found stable monensin at 4.2 parts per million or 4 grams/ton standard and reproduct
toFindString = "Stable NDA product";
paragraph = "NDA sampled and analyzed your “Sandhills Select Horse Feed found stable monensin at 4.2 parts per million or 4 grams/ton standard and reproductive product."
应单独搜索给定模式到字符串中的每个关键字
我是这样做的:
var splitedArray = paragraph.split(new RegExp(`(${toFindString .join("|")})`, "gi"));
splitedArray = ["NDA" , "sampled and analyzed your “Sandhills Select Horse Feed found", "stable", "monensin at 4.2 parts per million or 4 grams/ton standard and reproductive", "product" ]
我得到的结果是:
splitedArray = ["NDA" , "sampled and analyzed your “Sandhills Select Horse Feed found stable", "monensin at 4.2 parts per million or 4 grams/ton sta", "nda", "rd and re", "product", "ive", "product" ]
但我想要这样的结果:
var splitedArray = paragraph.split(new RegExp(`(${toFindString .join("|")})`, "gi"));
splitedArray = ["NDA" , "sampled and analyzed your “Sandhills Select Horse Feed found", "stable", "monensin at 4.2 parts per million or 4 grams/ton standard and reproductive", "product" ]
我使用的代码不会在“稳定”处搜索和拆分,因为在段落中它是“稳定”的。它从标准中搜索并拆分NDA,因为“NDA”出现在word standard中,“产品”关键字也出现在re产品ive中
我希望输出只作为输入关键字作为一个整体,它应该同时搜索大写和小写,但作为一个整体关键字,如nda或nda,而不是从一个词之间,就像它在standa和product中所做的那样
let toFindString=“稳定的NDA产品”;
让段落=“NDA对您的”山丘精选马饲料进行取样和分析,发现稳定的莫能菌素含量为百万分之4.2或4克/吨标准和生殖产品。”;
var splitedArray=段落.split(新的RegExp(`(${toFindString.join(“|”)}`,“gi”);
console.log(splitedArray);
这里需要的是
split()
并保留分隔符
- 在分隔符周围加括号,即
(稳定的| NDA |产品)
- 将
放入regexp以匹配单词边界,即\b
\b(稳定的| NDA |产品)\b
let toFindString=“稳定的NDA产品”;
让段落=“NDA对您的”山丘精选马饲料进行取样和分析,发现稳定的莫能菌素含量为百万分之4.2或4克/吨标准和生殖产品。”;
//结合上述解释中的第1点和第2点
let regex=“\\b(“+toFindString.split``.join`+”\\b”;
log(“使用了RegExp”,regex);
让splitedArray=段落.split(新的RegExp(regex,“i”))
.map(x=>x.trim())
.filter(x=>x);
console.log(splitedArray);
使用toFindString.join(“|”)
如果toFindString=“稳定的NDA产品”
。请显示实际值。对不起,我有点困惑。您想在一个字符串中搜索另一个字符串,并对每个匹配项进行拆分?请提供准确的问题陈述和代码段。很好-可能是trim()
?是,trim()
会很好,我会更新答案,但我会把后面的
留给OP来处理。你可以把\b
放在括号外,因为它的宽度为零。这会使内部更简单,就像新的RegExp(\\b(“+keywords.join(“|”)\\b“,“I”)
(g
标志在split
中也没有区别)。更新,非常感谢@Ry thnks,这对我有用。:-)