JQuery -正则表达式的问题;将空格转换为一个或两个字符的非中断空格(拉丁字母)

p3rjfoxz  于 5个月前  发布在  jQuery
关注(0)|答案(1)|浏览(53)

我是一个初学者,不知道该怎么做,使它在每一种情况下工作。提前感谢您的任何帮助🙈
我正在努力解决一个关于网站上文本分割的问题。我想在一个或两个字符的单词被空格或逗号和空格包围的情况下用非分割空格替换空格。我想防止在一行末尾有一个或两个字符的单词的情况
代码:

$(document).ready(function () {
  $("p, li, span, blockquote").each(function () {
    $(this)
      .contents()
      .filter(function () {
        return this.nodeType === 3; // Select only text nodes
      })
      .each(function () {
        // Replace at least one space or tab around one- and two-character non-breaking words with a space
        this.nodeValue = this.nodeValue.replace(
          /(\s|\t)+(\b\w{1,2}|\b\w{1,2})+(\s|\t)+/g,
          "\u00A0$2\u00A0"
        );
      });
  });
});

字符串
文本示例:“ala i marek na e taborecie i na stole,i,na co jest,e co“enter image description here

suzh9iv8

suzh9iv81#

希望这段代码对你有帮助。

$(document).ready(function () {
  $("p, li, span, blockquote").each(function () {
    $(this)
      .contents()
      .filter(function () {
        return this.nodeType === 3; // Select only text nodes
      })
      .each(function () {
        // Replace spaces around one- and two-character words with non-breaking spaces
        this.nodeValue = this.nodeValue.replace(
          /(?:\s|^)(\b\w{1,2}\b)(?:\s|$)/g,
          "\u00A0$1\u00A0"
        );
      });
  });
});

字符串
我是这样改变的:
1.添加(?:\s|^)(?:\s|$),以确保一个和两个字符的单词周围的空格正确匹配,而不会捕获它们。这样,只有一个和两个字符的单词将被替换为不间断的空格。
1.将替换模式更改为\u00A0$1\u00A0,其中$1表示匹配的单字符或双字符单词。

相关问题