admin管理员组文章数量:1244304
How do I check if a variable contains Chinese or Japanese characters? I know that this line works:
if (document.body.innerText.match(/[\u3400-\u9FBF]/))
I need to do the same thing not for the document but for a single variable.
How do I check if a variable contains Chinese or Japanese characters? I know that this line works:
if (document.body.innerText.match(/[\u3400-\u9FBF]/))
I need to do the same thing not for the document but for a single variable.
Share Improve this question edited Jun 26, 2012 at 11:35 user229044♦ 239k41 gold badges344 silver badges346 bronze badges asked Jun 26, 2012 at 11:34 waivywaivy 1371 gold badge2 silver badges8 bronze badges 3-
4
if (variable.match(/[\u3400-\u9FBF]/))
? – Esailija Commented Jun 26, 2012 at 11:35 -
You can apply
.match
to any string variable, not justdocument.body.innerText
. – user229044 ♦ Commented Jun 26, 2012 at 11:35 - Thank you. What I'm trying to do is to have the user select a portion of text from the document and assign it to my variable and after this check if the variable contains any Chinese character. I'm using var sel = window.getSelection() and then if (sel.match(/[\u3400-\u9FBF]/)) but it won't work. Strange thing is that if e.g I manually set sel = 漢字 it works fine but if I try to get it with window.getSelection() it won't – waivy Commented Jun 26, 2012 at 12:15
2 Answers
Reset to default 8.match
is a string method. You can apply it to anything that contains string. And, of course, to arbitrary variable.
In case you have something that is not string, most objects define .toString()
method that converts its content to some reasonable stringified form. When you retrieve selection from page, you get selection object. Convert it to string and then use match
on it: sel.toString().match(...)
.
afaik you can to the same with a variable... document.body.innerText
just returns the text of the body. Therefore you can just do
myvar.match(...)
Here's an example: http://snipplr./view/15357/
本文标签: javascriptHow can I check if variable contains ChineseJapanese charactersStack Overflow
版权声明:本文标题:javascript - How can I check if variable contains ChineseJapanese characters? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740184051a2237876.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论