删除 contenteditable div 中标签内字符串前后的空格

Remove spaces from before and after a string inside a tag in a contenteditable div

我正在尝试删除粗体标记中字符串前后的 space。

功能: 我创建了一个文本编辑器,当您键入文本和 select 文本并按粗体时,它会将文本加粗,当您按 html 按钮时,它会显示生成的 html下一个 window.

面临的问题: 当我尝试给制表符 space 然后输入文本时,select 文本与 space 一起加粗,它与空的 space 一起加粗。因此,当我在 html window 中查看 html 时,我能够在字符串的开头看到 space 。 我使用的代码从字符串中删除了所有 spaces,但我只想 trim 开始和开始,并且仍然像那样将 spaces 保留在字符串之间。任何帮助将不胜感激。

例如: 当您尝试将字符串与 space ' fdgfg gfdgfg fdgfg' 一起加粗时,这是它在编辑器中的外观。 生成的 html 看起来像 <b>&nbsp;&nbsp;fdgfg gfdgfg fdgfg</b> 所以我写了一个删除那些 space 的代码,但它删除了所有 space,只剩下 <b>fdgfggfdgfgfdgfg</b>。但我真正想要的是 <b>fdgfg gfdgfg fdgfg</b> 没有 spaces.

脚本:

//shows the html
  $("#show-html").click(function(){      
    var html = $("#textEditor").html();      
    html = html.replace(/&nbsp;|\s/gi, '');
  });

DEMO:

P.S: 它应该只删除开始和结束的白色 spaces,它应该保留中间的 spaces文本。例如 " abcd efgh " 这应该 trim 到 "abcd efgh" 不应删除文本之间的 space。

你可以试试.trim()

 str = "     something Here  ";
    console.log (str.trim());

或者这样使用

$.trim(str);

一种方法是遍历每个 <b> 元素,删除所有连续的空格,然后 trim 字符串。

Updated Example

$('#textEditor b').each(function () {
  $(this).text(function () {
    return $(this).text().replace(/\s+/g, ' ').trim();
  });
});

简单输入:

"     this     is   a  string  "

输出:

<b>this is a string</b>