7

我正在尝试像这样修剪从剑道编辑器获得的文本。

var html = "  T  "; // This sample text I get from Kendo editor
            console.log("Actual :" + html + ":");
            var text = "";
            try {
                // html decode
                var editorData = $('<div/>').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 = $('<div/>').html(html).text();
            text = editorData.trim();
            console.log("After trim :" + text + ":");
        }
        catch (e) {
            console.log("exception");
            text = html;
        }
4

5 回答 5

11

&nbsp;变成非换行符, \u00a0. JavaScript应该删除那些String#trim,但历史上浏览器实现在这方面有点错误。我认为这些问题已经在现代问题中得到了解决,但是......

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

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

那就是说要在开头替换所有空格或非换行符字符,然后什么都没有。

但是看到你的评论:

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

……那可能不是。

或者&nbsp;,您可以在转换为文本之前删除标记:

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

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

于 2016-05-23T09:43:39.867 回答
5

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

html.replace(/&nbsp;/g,' ').trim()
于 2018-01-07T10:41:29.943 回答
2

如果你使用 jQuery,你可以使用 jQuery.trim()

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

于 2018-01-08T09:18:08.690 回答
0

这个实施对我来说是成功的

s=s.replaceAll('&nbsp;', ' ').replaceAll('<br>', ' ').trim();
于 2021-10-23T20:13:16.270 回答
0

这些都不适合我。我想做的是"&nbsp;"只从字符串的开头或结尾删除,而不是从中间删除。所以我的建议是什么。

  let ingredients = str.replace(/&nbsp;/g, ' ');
  ingredients = this.ingredients.trim();
  ingredients = this.ingredients.replace(/\s/g, '&nbsp;');

var txt = 'aa&nbsp;&nbsp;cc&nbsp; &nbsp; ';
var result = txt.replace(/&nbsp;/g, ' ');
result = result.trim();
result = result.replace(/\s/g, '&nbsp;');
console.log(result);

于 2021-06-23T10:31:53.560 回答