This article example describes how JS obtains the first letter of Chinese pinyin and quickly finds the corresponding Chinese content on the page through the first letter of the pinyin. Share it for your reference, as follows:
Realize the effect:
Figure 1:
Figure 2:
The Chinese string "Take care" entered in this example has three characters that are polyphonic, so the alert dialog box shows a combination of multiple pronunciations;
How to achieve it?
How to quickly find the Chinese content on the page through the first letter of the pinyin?
The process principle is as follows: for example, to quickly search for some people's names, when the page is loaded, an index is established for all people's names to generate the correspondence between the first letter of the pinyin and the name; then monitor the keyboard event, when the user presses the keyboard, according to the key, it is worthwhile to see which letter is pressed, and then iterate over whether the same first letter of the pinyin exists in the index;
Here we also implement the function of searching according to letter combinations. The principle is as follows: When the user presses the key, we record the time of the key. If the interval between two consecutive keys is less than one second, it is considered a combination query. After adding the current key value to the previous key value, I won’t say much, just add the code!
Get the first letter of the pinyin:
var strChineseFirstPY = "";//The 375 polyphonic words var are included here oMultiDiff={"19969":"DZ","19975":"WM","19988":"QJ","20048":"YL","20056":"SC","20060":"NM","20094":"QG","20127":"QJ","20167":"QC","20193":"YG","20250":"KH ","20256":"ZC","20282":"SC","20285":"QJG","20291":"TD","20314":"YD","20340":"NE","20375":"TD","20389":"YJ","20391":"CZ","20415":"PB","20446":"YS","20447": "SQ","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20504":"TC","20608":"KG","20854":"QJ","20857":"ZC","20911":"PF","20985":"AW","21032 ":"PB","21048":"XQ","21049":"SC","21089":"YS","21119":"JC","21242":"SB","21273":"SC","21305":"YP","21306":"QO","21330":"ZC","21333":"SDC","21345":"QK","21 378":"CA","21397":"SC","21414":"XS","21442":"SC","21477":"JG","21480":"TD","21484":"ZS","21494":"YX","21505":"YX","21512":"HG","21523":"XH","21537":"PB", "21542":"PF","21549":"KH","21571":"E","21574":"DA","21588":"TD","21589":"O","21618":"ZC","21621":"KHA","21632":"ZJ","21654":"KG","21679":"LKG","21683":"KH ","21710":"A","21719":"YH","21734":"WOE","21769":"A","21780":"WN","21804":"XH","21834":"A","21899":"ZD","21903":"RN","21908":"WO","21939":"ZC","21956":"SA ","21964":"YA","21970":"TD","22003":"A","22031":"JG","22040":"XS","22060":"ZC","22066":"ZC","22079":"MH","22129":"XJ","22179":"XA","22237":"NJ","22244":"T D","22280":"JQ","22300":"YH","22313":"XW","22331":"YQ","22343":"YJ","22351":"PH","22395":"DC","22412":"TD","22484":"PB","22500":"PB","22534":"ZD","22549" :"DH","22561":"PB","22612":"TD","22771":"KQ","22831":"HB","22841":"JG","22855":"QJ","22865":"XQ","23013":"ML","23081":"WM","23487":"SX","23558":"QJ","2356 1":"YW","23586":"YW","23614":"YW","23615":"SN","23631":"PB","23646":"ZS","23663":"ZT","23673":"YG","23762":"TD","23769":"ZS","23780":"QJ","23884":"QK","24 055":"XH","24113":"DC","24162":"ZC","24191":"GA","24273":"QJ","24324":"NL","24377":"TD","24378":"QJ","24439":"PF","24554":"ZS","24683":"TD","24694":"WE"," 24733":"LK","24925":"TN","25094":"ZG","25100":"XQ","25103":"XH","25153":"PB","25170":"PB","25179":"KG","25203":"PB","25240":"ZS","25282":"FB","25303":"NA" ,"25324":"KG","25341":"ZY","25373":"WZ","25375":"XJ","25384":"A","25457":"A","25528":"SD","25530":"SC","25552":"TD","25774":"ZC","25874":"ZC","26044":"YW" ,"26080":"WM","26292":"PB","26333":"PB","26355":"ZY","26366":"CZ","26397":"ZC","26399":"QJ","26415":"ZS","26451":"SB","26526":"ZC","26552":"JG","26561":"T D","26588":"JG","26597":"CZ","26629":"ZS","26638":"YL","26646":"XQ","26653":"KG","26657":"XJ","26727":"HG","26894":"ZC","26937":"ZS","26946":"ZC","26999": "KJ","27099":"KJ","27449":"YQ","27481":"XS","27542":"ZS","27663":"ZS","27748":"TS","27784":"SC","27788":"ZD","27795":"TD","27812":"O","27850":"PB","27852 ":"MB","27895":"SL","27898":"PL","27973":"QJ","27981":"KH","27986":"HX","27994":"XJ","28044":"YC","28065":"WG","28177":"SM","28267":"QJ","28291":"KH","283 37":"ZQ","28463":"TL","28548":"DC","28601":"TD","28689":"PB","28805":"JG","28820":"QG","28846":"PB","28952":"TD","28975":"ZC","29100":"A","29325":"QJ","29 575":"SL","29602":"FB","30010":"TD","30044":"CX","30058":"PF","30091":"YSP","30111":"YN","30229":"XJ","30427":"SC","30465":"SX","30631":"YQ","30655":"QJ", "30684":"QJG","30707":"SD","30729":"XH","30796":"LG","30917":"PB","31074":"NM","31085":"JZ","31109":"SC","31181":"ZC","31192":"MLB","31293":"JQ","31400": "YX","31584":"YJ","31896":"ZN","31909":"ZY","31995":"XJ","32321":"PF","32327":"ZY","32418":"HG","32420":"XQ","32421":"HG","32438":"LG","32473":"GJ","32488 ":"TD","32521":"QJ","32527":"PB","32562":"ZSQ","32564":"JZ","32735":"ZD","32793":"PB","33071":"PF","33098":"XL","33100":"YA","33152":"PB","33261":"CX","33 324":"BP","33333":"TD","33406":"YA","33426":"WM","33432":"PB","33445":"JG","33486":"ZN","33493":"TS","33507":"QJ","33540":"QJ","33544":"ZC","33564":"XQ"," 33617":"YT","33632":"QJ","33636":"XH","33637":"YX","33694":"WG","33705":"PF","33728":"YW","33882":"SR","34067":"WM","34074":"YW","34121":"QJ","34255":"ZC ","34259":"XL","34425":"JH","34430":"XH","34485":"KH","34503":"YS","34532":"HG","34552":"XS","34558":"YE","34593":"ZL","34660":"YQ","34892":"XH","34928":" SC","34999":"QJ","35048":"PB","35059":"SC","35098":"ZC","35203":"TQ","35265":"JX","35299":"JX","35782":"SZ","35828":"YS","35830":"E","35843":"TD","35895": "YG","35977":"MH","36158":"JG","36228":"QJ","36426":"XQ","36466":"DC","36710":"JC","36711":"ZYG","36767":"PB","36866":"SK","36951":"YW","37034":"YX","3706 3":"XH","37218":"ZC","37325":"ZC","38063":"PB","38079":"TD","38085":"QY","38107":"DC","38116":"TD","38123":"YD","38224":"HG","38241":"XTC","38271":"ZC","3 8415":"YE","38426":"KH","38461":"YD","38463":"AE","38466":"PB","38477":"XJ","38518":"YT","38551":"WK","38585":"ZC","38704":"XS","38739":"LJ","38761":"GJ", "38808":"SQ","39048":"JG","39049":"XJ","39052":"HG","39076":"CZ","39271":"XT","39534":"TD","39552":"TD","39584":"PB","39647":"SB","39730":"LG","39748":"TP B","40109":"ZQ","40479":"ND","40516":"HG","40536":"HG","40583":"QJ","40765":"YQ","40784":"QJ","40840":"YK","40863":"QJG"};//Parameters, Chinese string //Return value: Pinyin first string array function makePy(str){if(typeof(str) != "string")throw new Error(-1,"Function makePy requires string type parameters!");var arrResult = new Array(); //Save the array of intermediate results for(var i=0,len=str.length;i<len;i++){//Get unicode code var ch = str.charAt(i);//Check whether the unicode code is within the processing range, if it is within, it returns the pinyin first letter of the code that is the Chinese character. If it is not there, it calls other functions to process arrResult.push(checkCh(ch));}//Processing arrResult, returning all possible pinyin first letter string arrays return mkRslt(arrResult);}function checkCh(ch){var uni = ch.charCodeAt(0);//If it is not within the Chinese character processing range and returns the original character, you can also call your own processing function if(uni > 40869 || uni < 19968)return ch; //dealWithOthers(ch);//Check whether it is a polyphonic word, it is processed as a polyphonic word, not just find the corresponding initial letter in the strChineseFirstPY string directly (oMultiDiff[uni]?oMultiDiff[uni]:(strChineseFirstPY.charAt(uni-19968)));}function mkRslt(arr){var arrRslt = [""];for(var i=0,len=arr.length;i<len;i++){var str = arr[i];var strlen = str.length;if(strlen == 1){for(var k=0;k<arrRslt.length;k++){arrRslt[k] += str;}}else{var tmpArr = arrRslt.slice(0);arrRslt = [];for(k=0;k<strlen;k++){//Copy the same arrRsltvar tmp = tmpArr.slice(0);//Add the current character str[k] to the end of each element for(var j=0;j<tmp.length;j++){tmp[j] += str.charAt(k);}//Connect the copied and modified array to arrRslt arrRslt = arrRslt.concat(tmp);}}} return arrRslt;}//Remove space function String.prototype.trim = function() { return this.replace(/(^/s*)|(/s*$)/g,""); }//View pinyin abbreviation function query(){ var str = document.getElementById("txtChinese").value.trim(); if(str == "") return; var arrRslt = makePy(str); alert(arrRslt);}Indexing code:
// Used to save the key-value pairs of the first letter and name var nameList = new Array();// When the page is loaded, initialize "nameList". window.onload = function(){ //Extract all names in the ID "divName" var div = document.getElementById("divName"); if (div){ var names = []; //Compatible with Firefox and Chrome; if (div.textContent){ //Replace all whitespace characters, including spaces, tabs, page breaks, etc. with spaces through replace(//s/ig," ").split("); }else{ names = div.innerText.replace(//s/ig," ").split(""); "); } for (var i = 0; i < names.length; i++){ if (names[i] != ""){ //Get the pinyin abbreviation var arrRslt = makePy(names[i]); //Add the correspondence between pinyin and Chinese to the array nameList.push(new Array(arrRslt.toString(), names[i])); } } }}Execute the search code:
var timezoneOffset = 0; //Record key time var keyCache = ""; //Record the letter combinations that are pressed continuously//Search when the keyboard letter is pressed document.onkeydown = function(event){ //Get the actual letter pressed by "event.keyCode" var key = String.fromCharCode(event.keyCode); var tz = new Date().getTime(); //Continuous key delay calculation, set to 1000 milliseconds, that is, 1 second if (tz - timezoneOffset > 1000){ //The delay exceeds one second, re-timed timezoneOffset = tz; keyCache = key; }else{ //The delay is within 1 second range, the filter character keyCache += key; } //Get the filter content length var keyLength = keyCache.length; var word = ""; //Record Chinese words that meet the conditions//Transfer the index and perform a search for (var i = 0; i < nameList.length; i++){ //Seave the equal length characters and compare the filter letter combination if (nameList[i][0].substr(0, keyLength) == keyCache){ if (word == ""){ word += nameList[i][1]; // Highlight the search results. The first result that meets the criteria must be cleared before the highlighting, so the second parameter here is passed as: true highlight(nameList[i][1].substr(0, keyLength), true); }else{ word += " " + nameList[i][1]; highlight(nameList[i][1].substr(0, keyLength), false); } } } //Show filter letter combinations in div var div = document.getElementById("divKeyCache"); if (div){ div.innerHTML = "Filter letter combinations: " + keyCache; }}Highlight code:
function encode(s){ return s.replace(/&/g,"&").replace(/</g,"<").replace(//g,">").replace(/([///./*/$/^])/g,"//$1");}function decode(s){ return s.replace(//[/./*/[/]/(/$/^])/g,"$1").replace(////g,">").replace(/</g,"<").replace(/&/g,"&");}// Highlight the character specified by "s", "clear": Whether to clear the previously highlighted content function highlight(s, clear){ if (s.length==0){ //alert('Search keyword not filled in!'); return false; } s=encode(s); var obj=document.getElementsByTagName("body")[0]; var t = ""; if (typeof clear != 'undefined' && clear){ //Clear the previously highlighted content t=obj.innerHTML.replace(/<span/s+class=.?highlight.?>([^<>]*)<//span>/gi,"$1"); obj.innerHTML=t; } var cnt=loopSearch(s,obj); t=obj.innerHTML var r=/{searchHL}(({(?!//searchHL})|[^{])*){//searchHL}/gt=t.replace(r,"<span class='highlight'>$1</span>"); obj.innerHTML=t;}function loopSearch(s,obj){ var cnt=0; if (obj.nodeType==3){ cnt=replace(s,obj); return cnt; } for (var i=0,c;c=obj.childNodes[i];i++){ if (!c.className||c.className!="highlight") cnt+=loopSearch(s,c); } return cnt;}function replace(s,dest){ var r=new RegExp(s,"g"); var tm=null; var t=dest.nodeValue; var cnt=0; if (tm=t.match(r)){ cnt=tm.length; t=t.replace(r,"{searchHL}"+decode(s)+"{/searchHL}") dest.nodeValue=t; } return cnt;}Highlight style:
<style>.highlight{background:red;font-weight:bold;color:white; font-size:24px;}</style>HTML:
<body><form><table><td><span>Please enter the Chinese string:</span><input type="text" id="txtChinese" size="30" value="Take care"><input type="button" onclick="query()" value="View pinyin abbreviation"></td></tr></table></form><div id="divName"> <span><a href="#uid23">Chen Xiaowei</a></span> <span><a href="#uid23">Zhang Ningning</a></span> <span><a href="#uid23">Li Xu</a></span> <span><a href="#uid23">Li Xu</a></span> <span><a href="#uid23">Wang Changfeng</a></span> <span><a href="#uid23">Liu Qiyin</a></span> <span><a href="#uid23">Chen Zhixin</a></span> <span><a href="#uid23">Huang Zhihua</a></span> <span><a href="#uid23">Gao Yuehua</a></span> <span><a href="#uid23">Li Chengxin</a></span> <span><a href="#uid23">Zhao Lin</a></span> <span><a href="#uid23">Liu Jian</a></span> <span><a href="#uid23">Wang Ying</a></span> <span><a href="#uid23">Bai Xikang</a></span> <span><a href="#uid23">Zhang Jianbo</a></span> <span><a href="#uid23">Lin Feng</a></span></div><br /><br /><div style="font-size:14px; font-weight:bold;">Search through the first letter of the name, keep the page focused, and press the letter combination continuously. For example: If you want to find "Huang Zhihua", you can press the letter continuously: HZH</div><div id="divKeyCache">Filter the letter combination: </div></body>
Click here to download the complete example code.
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript Search Algorithm and Skills", "Summary of JavaScript Value Transfer Operation Skills", "Summary of JavaScript Encoding Operation Skills", "Summary of JSON Operation Skills in JavaScript", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Errors and Debugging Skills", "Summary of JavaScript Data Structures and Algorithm Skills" and "Summary of JavaScript Mathematical Operation Usage"
I hope this article will be helpful to everyone's JavaScript programming.