PSR*_*PSR 5 javascript jquery trim kendo-editor
我试图修剪我从剑道编辑器得到的文本.
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;
}
Run Code Online (Sandbox Code Playgroud)
此代码位于单独的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;
}
Run Code Online (Sandbox Code Playgroud)
成为不断裂空格字符,\u00a0.JavaScript的String#trim是应该消除这些,但历史上的浏览器实现已经在这方面有点马车.我认为这些问题已在现代问题上得到解决,但......
如果您遇到的浏览器没有正确实现它,您可以使用正则表达式解决这个问题:
text = editorData.replace(/(?:^[\s\u00a0]+)|(?:[\s\u00a0]+$)/g, '');
Run Code Online (Sandbox Code Playgroud)
这表示在开头和结尾都没有替换所有空格或非空格字符.
但看到你的评论:
当我单独运行这段代码时,它对我来说很好.但在应用中它失败了.
......可能不是这样.
或者,您可以 在转换为文本之前删除标记:
html = html.replace(/(?:^(?: )+)|(?:(?: )+$)/g, '');
var editorData = $('<div/>').html(html).text();
text = editorData.trim();
Run Code Online (Sandbox Code Playgroud)
这会 在将标记转换为文本之前删除开头或结尾处的任何s.
小智 5
从字符串中修剪不间断空格的最简单方法是
html.replace(/ /g,' ').trim()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5484 次 |
| 最近记录: |