日期:2014-05-16 浏览次数:20358 次
function searchReg(keyWord){ var str = "@xinlang|新浪|1@souhu|搜狐|2@wangyi|网易|3@baidu|百度|4@tengxun|腾讯|5@kaixinwang|开心网|6@renrenwang|人人网|7@1haodian|1号店|8@"; var reg = new RegExp("[^@]*" + keyWord + "[^@]*","gi"); var arr= []; str = str.replace(reg, function(a){ arr.push(a); }); console.log(arr); } searchReg("x")
<!doctype html> <html> <head> <title>tank fighting</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <input id="inputbox" type="text" value="" /> <input id="btn" type="button" value="search" /> <script> var str = "0@xinlang|新浪|1@souhu|搜狐|2@wangyi|网易|3@baidu|百度|4@tengxun|腾讯|5@kaixinwang|开心网|6@renrenwang|人人网|7@1haodian|1号店|8@"; document.getElementById('btn').onclick = function(){ var val = document.getElementById('inputbox').value, reg = new RegExp("(\\w)*@(?:\\w+\\|)?"+val), ret = reg.exec(str); alert(ret[1]); } </script> </body> </html>