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

Regex match a sentence in a paragraph that contains new lines

我基本上有一段文字在htmldiv。按clicking/activating一个按钮,我想高亮显示一定长度的文字。因此,我需要找到它的索引并添加带有 class =highlight 的跨度。

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

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

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

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

而且我无法 "ulter" innerHTML,例如从文本中删除 spaces/new 行。

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

这不起作用:

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

您可以 replace 换行符 单个 spacematch .

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);

好吧,这就是我会做的。

只需将文本按 \n 拆分,然后与 " " 合并,使其成为单行句子格式。现在您可以使用 .includes 来检查您要匹配的文本是否是其他文本的一部分

var text = "The quick brown fox jumps over the lazy dog",
    stringWithBreakLines = `The quick brown
fox jumps over
the lazy dog
this is some additional
text in html`;
 
console.log(stringWithBreakLines.split("\n").join(" ").includes(text))

当您搜索单词之间的任何空格分隔(不仅仅是空格)时,您需要将搜索模式中的空格替换为一般的空格标记。这将起作用:

var regex = text.split(/\s+/).join('\s+');
var search_regexp = new RegExp(text, 'm');
innerHTML.search(search_regexp);

split(/\s+/).join('\s+')的效果是:

  1. 在任意数量的空格上拆分输入文本,生成单词数组,
  2. 使用匹配一个或多个空白字符的 \s+ 正则表达式标记来连接单词。这包括换行符和制表符。