Codewars-Javascript训练手册:正则表达式(Regular Expressions)
Autocomplete! Yay!(字符串自動補全)
The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return an empty array.(autocomplete 函數(shù)輸入一個字符串和字典數(shù)組,返回開頭是該字符串的值,返回值的個數(shù)最多限制為5個,無匹配則返回空數(shù)組)
對于輸入字符串的要求:Any input that is NOT a letter should be treated as if it is not there. For example, an input of “$%^” should be treated as “” and an input of “ab*&1cd” should be treated as “abcd”.
Example:
autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport']初始解決方案:
function autocomplete(input, dictionary){var str = input.replace(/[^A-Za-z]+/g,'');var pattern = new RegExp('^'+str,'i');var temp = dictionary.filter(function(value){if(pattern.test(value)){return true;}else{return false;}});return temp.length<6?temp:temp.slice(0,5); }知識點:創(chuàng)建一個正則表達(dá)式有兩種方式,一是直接量語法var reg = /pattern/ 適用于正常輸入的正則表達(dá)式,二是創(chuàng)建 RegExp 對象,語法是new RegExp(pattern, attributes);例如:var reg = new RegExp('pattern','gi') 第二種語法適用于對正則表達(dá)式的拼接。注意第一種語法直接輸入正則的內(nèi)容即可,解釋器通過/×××/ 這樣的形式確認(rèn)類型為RegExp對象。而第二種語法則類似字符串的寫法。
優(yōu)化代碼:
所以,最簡的代碼是:
function autocomplete(input, dictionary){var r = new RegExp('^' + input.replace(/[^a-z]/gi,''), 'i');return dictionary.filter(function(w){ return r.test(w); }).slice(0, 5); }這正是Codewars上得票最高的答案。
Credit Card Mask(信用卡字符加密)
給出一個函數(shù)maskify用“#”字符替換超過4個字符的字符串,4個字符則返回自身。例如:
maskify("4556364607935616") == "############5616" maskify( "64607935616") == "#######5616" maskify( "1") == "1" maskify( "") == ""本以為可以用一個正則表達(dá)式可以解決問題,然而發(fā)現(xiàn)RegExp {X} 量詞中x必須為數(shù)字。于是將原字符串分割開進(jìn)行匹配,代碼如下:
function maskify(cc) { var len = cc.length; if(len<5){return cc; }else{ //對字符串分割后進(jìn)行正則匹配return cc.slice(0,len-4).replace(/\w/g,'#') + cc.slice(len-4); } }然而,我忘了正則的另外一個用法:/regexp(?=n)/ ?=n 量詞匹配任何其后緊接指定字符串 n 的字符串,但匹配的內(nèi)容并不包括指定字符串n。
所以,Codewars最簡短的代碼正是如此:
轉(zhuǎn)載于:https://www.cnblogs.com/xihe/p/6138615.html
總結(jié)
以上是生活随笔為你收集整理的Codewars-Javascript训练手册:正则表达式(Regular Expressions)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JQ实现三个Select下拉框互斥
- 下一篇: 今天改bug遇到一个ie8样式错乱问题