javascript 如何检查变量是否包含中文/日文字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11206443/
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-26 12:23:43  来源:igfitidea点击:

How can I check if variable contains Chinese/Japanese characters?

javascriptjqueryhtml

提问by waivy

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.

我需要为单个变量而不是文档做同样的事情。

回答by Oleg V. Volkov

.matchis a string method. You can apply it to anything that contains string. And, of course, to arbitrary variable.

.match是一个字符串方法。您可以将其应用于任何包含字符串的内容。而且,当然,任意变量。

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 matchon it: sel.toString().match(...).

如果您有一些不是字符串的内容,大多数对象定义.toString()了将其内容转换为某种合理的字符串化形式的方法。当您从页面检索选择时,您将获得选择对象。将其转换为字符串,然后match在其上使用:sel.toString().match(...).

回答by Atmocreations

afaik you can to the same with a variable... document.body.innerTextjust returns the text of the body. Therefore you can just do

afaik 你可以用一个变量来做同样的事情......document.body.innerText只返回正文的文本。因此你可以做

myvar.match(...)

Here's an example: http://snipplr.com/view/15357/

这是一个例子:http: //snipplr.com/view/15357/