检测和 JavaScript 的空格
我正在尝试读取 contentEditable
div 的内容并提取当前活动的单词。 IE。刚刚输入的单词或修改过的单词。
我最初的方法是:
- 将字符串获取为
innerHTML
- 使用函数获取光标位置(现在我可以找到被修改的单词)
- 向后读取直到找到空格(逐个字符比较)
- 从中提取单词找到的空间点。
但问题是浏览器有时会将空格转换为
,有时则不会(如果只有一个空格则没有问题)。然后我决定使用第二个循环来读取 5 个字符(如果找到 a ;
)并进行检查。但这似乎效率很低。那么有没有更好的方法来做到这一点呢?
I'm trying to read the content of a contentEditable
div and extract the currently active word. ie. the word which was just entered or one which was modified.
My initial approach was:
- get string as
innerHTML
- get cursor position using a function (now I can find the word that was modified)
- read backwards till a space is found (character by character comparison)
- extract the word from the point of space found.
But the problem is that the browser sometimes converts the spaces to
and sometimes doesn't (There is no problem if there is only one space). Then I decided to using a second loop to read in 5 chars if a ;
is found and check against that. But this is seems very inefficient. So is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
String.fromCharCode(160)
为我工作。它代表if(str == ' ')
在 if 条件下不起作用,trim() 也不起作用;但是 if(str == String.fromCharCode(160)) 有效。要检查正常空间,请使用
if(str.trim() == '')
String.fromCharCode(160)
worked for me. It stands forif(str == ' ')
was not working in if condition, neither did trim(); butif(str == String.fromCharCode(160))
worked.For checking normal space use
if(str.trim() == '')
我找到了一个解决方法。以前,我使用innerHTML 来获取内容。
现在,我使用
targ.firstChild.nodeValue
,其中 targ 是需要其内容的元素。然后使用str.charCodeAt(i)==32 || 检查str.charCodeAt(i)==160
。这效果很好。
I found a workaround. Previously, I was using innerHTML to get the contents.
Now, I'm using
targ.firstChild.nodeValue
where targ is the element whose content is needed.Then checking withstr.charCodeAt(i)==32 || str.charCodeAt(i)==160
.This works well.
我想你正在寻找的是这里:Javascript 中的不间断空格。
I think what you are looking is here : non-breaking space in Javascript.