在javascript中修剪和修改值 [英] Trim &nbsp values in javascript
问题描述
我正在尝试修剪我从kendo编辑器获得的文本。
I am trying to trim the text which I get from kendo editor like this.
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生成)。当页面加载时,修剪不起作用。但是,当我在开发人员工具控制台窗口中运行相同的代码时,它的工
为什么不工作?
This code is in seperate js file ( generated from typescript). When the page loads the trimming is not working. But when I run the same code in developer tools console window its working. Why it is not working?
添加打字稿代码
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;
}
推荐答案
& nbsp;
成为非休息空间角色, \ u00a0
。 JavaScript的 String#修剪
是 假设删除那些,但历史上浏览器实现在这方面有点麻烦。我认为这些问题已经在现代问题上得到了解决,但是...
becomes a non-break-space character, \u00a0
. JavaScript's String#trim
is supposed to remove those, but historically browser implementations have been a bit buggy in that regard. I thought those issues had been resolved in modern ones, but...
如果你正在遇到没有实现它的浏览器正确地说,你可以用正则表达式解决这个问题:
If you're running into browsers that don't implement it correctly, you can work around that with a regular expression:
text = editorData.replace(/(?:^[\s\u00a0]+)|(?:[\s\u00a0]+$)/g, '');
这表示在开头和结尾都没有替换所有空格或非空格字符。
That says to replace all whitespace or non-break-space chars at the beginning and end with nothing.
但看到你的评论后:
当我运行这段代码时另外,它对我来说很好。但是在应用程序中失败了。
When I run this piece of code separately, it is working fine for me. But in application its failing.
...可能不是它。
或者,您可以在转换为文字前删除& nbsp;
标记:
Alternately, you could remove the
markup before converting to text:
html = html.replace(/(?:^(?: )+)|(?:(?: )+$)/g, '');
var editorData = $('<div/>').html(html).text();
text = editorData.trim();
删除任何& nbsp;
s在将标记转换为文本之前的开头或结尾。
That removes any
s at the beginning or end prior to converting the markup to text.
这篇关于在javascript中修剪和修改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!