我正在尝试修剪从剑道编辑器获得的文本,如下所示。
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 文件中(从打字稿生成)。当页面加载时,修剪不起作用。但是当我在开发人员工具控制台窗口中运行相同的代码时,它就可以工作了。 为什么不起作用?
添加打字稿代码
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;
}
成为非换行空格字符、\u00a0
。 JavaScript 的 String#trim
应该 删除这些,但历史上浏览器实现在这方面有点错误。我以为这些问题在现代已经得到解决,但是......
如果您遇到的浏览器无法正确实现它,您可以使用正则表达式来解决这个问题:
text = editorData.replace(/(?:^[\s\u00a0]+)|(?:[\s\u00a0]+$)/g, '');
这表示将开头和结尾处的所有空格或非换行符替换为空。
但是看到你的评论:
当我单独运行这段代码时,它对我来说工作得很好。但在应用中却失败了。
...可能不是这样。
或者,您可以在转换为文本之前删除
标记:
html = html.replace(/(?:^(?: )+)|(?:(?: )+$)/g, '');
var editorData = $('<div/>').html(html).text();
text = editorData.trim();
这会在将标记转换为文本之前删除开头或结尾处的所有
。
从字符串中删除不间断空格的最简单方法是
html.replace(/ /g,' ').trim()
如果您使用 jQuery,则可以使用 jQuery.trim()
函数从提供的字符串的开头和结尾删除所有换行符、空格(包括不间断空格)和制表符。 来源
这些都不适合我。我想要做的是仅从字符串的开头或结尾删除
" "
,而不是从中间删除。那么我的建议是。
let ingredients = str.replace(/ /g, ' ');
ingredients = this.ingredients.trim();
ingredients = this.ingredients.replace(/\s/g, ' ');
var txt = 'aa cc ';
var result = txt.replace(/ /g, ' ');
result = result.trim();
result = result.replace(/\s/g, ' ');
console.log(result);
这个实施对我来说是成功的
s=s.replaceAll(' ', ' ').replaceAll('<br>', ' ').trim();
我正在使用
str.replace(/\s{2,}/g, '');
这会修剪单词之间的双空格,这也是不正确的。
附注 下面的方法不起作用
str.replace(/ /g, '');
str.replaceAll(" ", '');
str.replace(/\xa0/g, '')