gpt4 book ai didi

javascript - 正则表达式匹配包含新行的段落中的句子

转载 作者:行者123 更新时间:2023-11-29 23:22:52 25 4
gpt4 key购买 nike

我基本上在 html div 中有一段文本。通过单击/激活按钮,我想突出显示一定长度的文本。因此,我需要找到它的索引并向其添加类 =highlight 的跨度。

因此,我想匹配 innerHtml 文本中的一个句子,例如:

var text = "The quick brown fox jumps over the lazy dog".

但是,段落可能会将句子分成多行,例如:

innerHTML = 
"The quick brown
fox jumps over
the lazy dog"

而且我不能以任何方式“破坏”innerHTML,例如从文本中删除空格/新行。

我似乎无法想到或找到正确的正则表达式序列来实现它。

这行不通:

var search_regexp = new RegExp(text, 'm');
innerHTML.search(search_regexp);

最佳答案

您可以通过单个空格匹配替换换行符

var fnReplaceLR = ( str ) => str.replace(/\s+/g, " " ); //method to replace line-breaks and other consecutive multiple spaces with single space.
var text = "The quick brown fox jumps over the lazy dog";
var innerHTML =
`The quick brown
fox jumps over
the lazy dog`;
var search_regexp = new RegExp( fnReplaceLR( text ) ); //no need for m modifier now
fnReplaceLR( innerHTML ).match( search_regexp ); //match the string

演示

var fnReplaceLR = (str) => str.replace(/\s+/g, " "); //method to replace line-breaks and other consecutive multiple spaces with single space.
var text = "The quick brown fox jumps over the lazy dog";
var innerHTML =
`The quick brown
fox jumps over
the lazy dog`;
var search_regexp = new RegExp(fnReplaceLR(text)); //no need for m modifier now
var output = fnReplaceLR(innerHTML).match(search_regexp); //match the string
console.log(output);

关于javascript - 正则表达式匹配包含新行的段落中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com