检测   和空间与 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5308797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:44:16  来源:igfitidea点击:

Detect   and space with JavaScript

javascriptwhitespacehtml-entities

提问by Diff.Thinkr

I'm trying to read the content of a contentEditablediv and extract the currently active word. ie. the word which was just entered or one which was modified.

我正在尝试读取contentEditablediv的内容并提取当前活动的单词。IE。刚刚输入的单词或修改过的单词。

My initial approach was:

我最初的做法是:

  1. get string as innerHTML
  2. get cursor position using a function (now I can find the word that was modified)
  3. read backwards till a space is found (character by character comparison)
  4. extract the word from the point of space found.
  1. 获取字符串为 innerHTML
  2. 使用函数获取光标位置(现在我可以找到被修改的单词)
  3. 向后读取直到找到一个空格(逐字符比较)
  4. 从找到的空间点提取单词。

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?

但问题是浏览器有时会转换空格 ,有时不会(如果只有一个空格没有问题)。然后我决定使用第二个循环读取 5 个字符,如果a ;找到并检查它。但这似乎非常低效。那么有没有更好的方法来做到这一点?

回答by Diff.Thinkr

I found a workaround. Previously, I was using innerHTML to get the contents. Now, I'm using targ.firstChild.nodeValuewhere targ is the element whose content is needed.Then checking with str.charCodeAt(i)==32 || str.charCodeAt(i)==160 .

我找到了一个解决方法。以前,我使用innerHTML 来获取内容。现在,我使用targ.firstChild.nodeValuewhere targ 是需要其内容的元素str.charCodeAt(i)==32 || str.charCodeAt(i)==160 。然后使用.

This works well.

这很好用。

回答by Sacky San

String.fromCharCode(160)worked for me. It stands for  character. if(str == ' ')was not working in if condition, neither did trim(); but if(str == String.fromCharCode(160))worked.

String.fromCharCode(160)对我来说有效。它代表 性格。if(str == ' ')在 if 条件下不工作,trim() 也不工作;但if(str == String.fromCharCode(160))工作。

For checking normal space use if(str.trim() == '')

用于检查正常空间使用情况 if(str.trim() == '')

回答by Halil ?zgür

I think what you are looking is here : non-breaking space in Javascript.

我认为您正在寻找的内容在这里:Javascript 中的不间断空格