在javascript中修剪值

我试图修剪我从剑道编辑器得到的文本。

var html = "  T  "; // This sample text I get from Kendo editor console.log("Actual :" + html + ":"); var text = ""; try { // html decode var editorData = $('
').html(html).text(); text = editorData.trim(); console.log("After trim :" + text + ":"); } catch (e) { console.log("exception"); text = html; }

此代码位于单独的js文件中(从typescript生成)。 当页面加载时,修剪不起作用。 但是,当我在开发人员工具控制台窗口中运行相同的代码时,它的工 为什么不工作?

添加打字稿代码

  const html: string = $(selector).data("kendoEditor").value(); console.log("Actual :" + html + ":"); let text: string = ""; try { // html decode var editorData = $('
').html(html).text(); text = editorData.trim(); console.log("After trim :" + text + ":"); } catch (e) { console.log("exception"); text = html; }

  成为一个非rest空间的角色 , \u00a0 。 JavaScript的String#trim 应该会删除它们 ,但历史上浏览器实现在这方面有点麻烦。 我认为这些问题已在现代问题上得到解决,但……

如果您遇到的浏览器没有正确实现它,您可以使用正则表达式解决这个问题:

 text = editorData.replace(/(?:^[\s\u00a0]+)|(?:[\s\u00a0]+$)/g, ''); 

这表示在开头和结尾都没有替换所有空格或非空格字符。

但看到你的评论:

当我单独运行这段代码时,它对我来说很好。 但在应用中它失败了。

……可能不是这样。

或者 ,你可以删除  转换为文本前的标记:

 html = html.replace(/(?:^(?: )+)|(?:(?: )+$)/g, ''); var editorData = $('
').html(html).text(); text = editorData.trim();

这删除了任何  在将标记转换为文本之前的开头或结尾处的s。

如果您使用的是jQuery,可以使用jQuery.trim()

函数从提供的字符串的开头和结尾删除所有换行符,空格(包括不间断空格)和制表符。 资源

从字符串中修剪不间断空格的最简单方法是

 html.replace(/ /g,' ').trim()