有没有一种方法可以在带有换行符(\ n)的字符串中搜索子字符串?

时间:2019-08-07 11:54:04

标签: javascript html

我有一个文本,里面带有\n个字符,并且我想通过在文本中用标记将其段包裹起来来突出显示一组短语。问题是,如果有\n符号,则无法在文本中找到此短语。

我尝试从文本中替换\n,但是我需要在突出显示后恢复它们。

let text = 'Looking For An Enterprise Test Authoring Platform?\n
Learn More About Gauge\n
Watch our video to learn if Gauge can help you.'

let phrases = ["Authoring Platform? Learn More", "Gauge Watch our video", "can help you"]

const highlight = (phrase) => text.replace(phrase, `<mark style="background: #4CAF50">${phrase}</mark>`)

phrases.map(phrase=> text = highlight(phrase))

只有最后一个短语与文本匹配。我正在寻找忽略\n并匹配所有短语的方法。也许还有另一种方法可以解决这个问题。我将不胜感激!

3 个答案:

答案 0 :(得分:1)

一种选择是遍历该短语并创建动态正则表达式。将每个\s替换为(?:\n)*。这将创建一个动态正则表达式,如下所示:

/Authoring(?:\n)* Platform\?(?:\n)* Learn(?:\n)* More/

然后使用$& replace text匹配子字符串。这将保留原始字符串中的\n

let text = 'Looking For An Enterprise Test Authoring Platform?\n Learn More About Gauge\n Watch our video to learn if Gauge can help you.'

let phrases = ["Authoring Platform? Learn More", "Gauge Watch our video", "can help you"]

// https://stackoverflow.com/a/494122
const escape = str => str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")

phrases.forEach(p => {
  const regex = new RegExp( escape(p).replace(/\s/g, '\(?:\n)* ') )
  text = text.replace(regex, `<mark style="background:#4CAF50">$&</mark>`)
})

console.log(text)

escape函数取自here。它用于从每个词组中转义?之类的元字符

这是使用reduce和一些辅助函数的替代方法:

const text = 'Looking For An Enterprise Test Authoring Platform?\n Learn More About Gauge\n Watch our video to learn if Gauge can help you.',
      phrases = ["Authoring Platform? Learn More", "Gauge Watch our video", "can help you"],
      escape = str => str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"),
      createReg = p => new RegExp( escape(p).replace(/\s/g, '\(?:\n)* ') ),
      replaceWith = '<mark style="background:#4CAF50">$&</mark>',
      output = phrases.reduce((a, p) => a.replace(createReg(p), replaceWith), text)

console.log(output)

答案 1 :(得分:0)

您可以通过选择第一个单词并将句子与此简单的正则表达式\bfirstWord (.*?) endWord\b

相匹配
let text = 'Looking For An Enterprise Test Authoring Platform?\n
            Learn More About Gauge\n
            Watch our video to learn ifGauge can help you.';

 text.match(/\Gauge (.*?) video\b/gis)
 // ["Gauge↵↵Watch our video"]
 // \n character is being preserved

这可能会使它更加复杂,因为您需要找到每个句子的第一个和最后一个词。

答案 2 :(得分:-1)

只需从字符串中删除\ n,然后像这样检查字符串中的短语即可。

let text = 'Looking For An Enterprise Test Authoring Platform?\n
Learn More About Gauge\n
Watch our video to learn ifGauge can help you.';

let phrases = ["Authoring Platform? Learn More", "Gauge Watch our video", "can help you"];

//string without \n
let plainText = text.replace("\n", "");

const highlight = (phrase) => {
    return plainText.replace(phrase, `<mark style="background: #4CAF50">${phrase}</mark>`)
}


phrases.map(phrase=> {
    text = highlight(phrase)
})