怎么将文字转换拼音 javascript

发布网友

我来回答

6个回答

热心网友

首先:需要一个汉字拼音对应的表,可以用json格式,也可以用类例如:

{'hao':'\u58d5\u568e\u8c6a\u6beb\u90dd\u597d\u8017\u53f7\u6d69\u8585\u55e5\u5686\u6fe0\u704f\u660a\u7693\u98a2\u869d'} 里面的"\u58d5"是汉字的代码
然后通过查找你的汉字和里面的匹配,找到前面的拼音,原理是这样的,但是在匹配的时候怎么快,这个在网上有人写好的插件,也可以自己写,一般情况是:遍历里面的所有的,直到找到或者遍历完成,当然汉字的变慢在你的范围内。还有另外的,就是将汉字编码是有顺序大小的,可以排好序,然后再找前面的英文。

热心网友

操作环境:Visual Studio.Net2005
操作系统:window vista home premium
IE: IE7

一个简单且实用的JS中文转换首字母拼音码的函数,代码量少,功能实用,不支持多音字的转换!

[jscript] view plain copy
<script language="javascript" type="text/javascript">

function getPYCode(str)
{
var result = "";

for(var i=0;i<str.length;i++)
{
result += getPY(str.charAt(i).toString());
}
document.getElementById("lblResult").innerHTML = result;
}

function getPY(s)
{
if(s !="") {
execScript("tmp=asc(/""+s+"/")", "vbscript");
tmp = 65536 + tmp;

var py = "";
if(tmp>=45217 && tmp<=45252) {
py = "A"
} else if(tmp>=45253 && tmp<=45760) {
py = "B"
} else if(tmp>=45761 && tmp<=46317) {
py = "C"
} else if(tmp>=46318 && tmp<=46825) {
py = "D"
} else if(tmp>=46826 && tmp<=47009) {
py = "E"
} else if(tmp>=47010 && tmp<=47296) {
py = "F"
} else if((tmp>=47297 && tmp<=47613) || (tmp == 63193)) {
py = "G"
} else if(tmp>=47614 && tmp<=48118) {
py = "H"
} else if(tmp>=48119 && tmp<=49061) {
py = "J"
} else if(tmp>=49062 && tmp<=49323) {
py = "K"
} else if(tmp>=49324 && tmp<=495) {
py = "L"
} else if(tmp>=496 && tmp<=50370) {
py = "M"
} else if(tmp>=50371 && tmp<=50613) {
py = "N"
} else if(tmp>=50614 && tmp<=50621) {
py = "O"
} else if(tmp>=50622 && tmp<=50905) {
py = "P"
} else if(tmp>=50906 && tmp<=51386) {
py = "Q"
} else if(tmp>=51387 && tmp<=51445) {
py = "R"
} else if(tmp>=51446 && tmp<=52217) {
py = "S"
} else if(tmp>=52218 && tmp<=52697) {
py = "T"
} else if(tmp>=52698 && tmp<=52979) {
py = "W"
} else if(tmp>=52980 && tmp<=53688) {
py = "X"
} else if(tmp>=536 && tmp<=54480) {
py = "Y"
} else if(tmp>=54481 && tmp<=622) {
py = "Z"
} else {
py =s.charAt(0);
}
return py;
}
}

</script>

HTML:
<label id="lblResult"></label> <input type="text" onkeydown="getPYCode(this.value)" onkeyup="getPYCode(this.value)" />

热心网友

目标

通过Js将中文转化为拼音

插件

Jspinyin

实现

var pinyin = new Pinyin();
alert(pinyin.getFullChars('你好中国'));

    4.下载链接

Github : https://github.com/chinalu/JSPinyin

    5.参考文档

http://my.oschina.net/tommyfok/blog/202412 非本人编写。

热心网友

JavaScript没有内置这种中文拼音,所以需要自己做一个类似于字库的东西,推荐用Unicode来做!

热心网友

JavaScript没有这种方法可以转换的。

热心网友

参考资料:http://www.jb51.net/article/33851.htm

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com