在javascript中,如何将换行符添加到6个单词后的大块文本上?

时间:2018-09-22 09:51:19

标签: javascript regex

我有以下正则表达式,可在80个字符后添加换行符 但我想在7个字之后添加换行符。

long_string.replace(/(.{80})/g, "$1<br>")

3 个答案:

答案 0 :(得分:1)

这将起作用

const long_string = "one two three four five six <script>alert('pwnd');<\/script> bla bla bla bla bla bla bla bla bla";

//first replace html tags then add line breaks
const output = long_string.replace(/<([^>]+)>/g,"&lt$1&gt").replace(/((\S+\s){7})/g, "$1<br>");

document.getElementById("output").innerHTML = output;
<div id="output"></div>

答案 1 :(得分:0)

替代品正在使用减速器

const long_string = "I have following regex which adds line break after 80 characters but i want to add line break after 7 words.";

console.log(addBreak(long_string, 7));

function addBreak(longstr, breakAt) {
  let n = 0;
  return longstr
    .split("")
    .reduce( (str, c) => {
      n += n < breakAt && /[ ;:,]/.test(c) ? 1 : 0;
      return n === breakAt ? (n += 1, `${str}<br>`) : `${str}${c}`;
    }, "" );
}

答案 2 :(得分:0)

您可以在word character中匹配character class \w,并添加您也可以匹配的字符,例如[\w.,!?]

然后在匹配一次或多次[\w.,!?]+的组中捕获,然后捕获与空格和字符集类的一次或多次6次匹配的重复模式(?: [\w.,!?]+){6}。替换为$1<br>

([\w.,!?]+(?: [\w.,!?]+){6})

let long_string = `This is a test one two three. This, is a test one two three! This? This is a test one two....`;
console.log(long_string.replace(/([\w.,!?]+(?: [\w.,!?]+){6})/g, "$1<br>"));