js 截取字符串 求个正则表达式

liminlimin 2008-02-29 04:37:55
index2.php?option=content&task=showcategory&fun=show
想取得task的值.求个正则表达式谢谢
...全文
694 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复
干脆测试代码也给你:

<script language=javascript>
function getValue(key,str){
try{ return str.match(new RegExp(key+'=(\\w+)&?'))[1];}catch(e){alert('no value of '+key);return null}
}
function get(o){
alert(getValue(o.value,document.getElementById('content' ).value));
}
</script>
<input id='content' type="text" value="index2.php?option=content&task=showcategory&fun=show" />
<input type="button" value='option' onclick="get(this)"/>
<input type="button" value='task' onclick="get(this)"/>
<input type="button" value='fun' onclick="get(this)"/>
<input type="button" value='error' onclick="get(this)"/>
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复
如果不用2楼的,另一个加点可靠性保障。

function getValue(key,str){
try{
return str.match(new RegExp(key+'=(\\w+)&?'))[1];
}catch(e){
alert('no value of '+key);
return null;
}
}
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复
2楼那个肯定没问题。另一个要用的话,可以这么改。

function getValue(key,str){
return str.match(new RegExp(key+'=(\\w+)&?'))[1];
}

推荐用2楼的。

function getValue(key,str){
var a = str.split(/\?|=|&/);
for(var i=0,len=a.length;i<len;i++)if(a[i]==key)return a[i+1];
return null;
}
liminlimin 2008-02-29
  • 打赏
  • 举报
回复
index2.php?option=content&task=showcategory和index2.php?option=content&task=showcategory&fun=show
这样能都获取到
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复
没问题啊。

<script language=javascript>
function getValue(key,str){
return str.match(new RegExp(key+'=(\\w+)&'))[1];
}
</script>
<input id='content' type="text" value="index2.php?option=content&task=showcategory&fun=show" />
<input type="button" value='点点看' onclick="alert(getValue('task',document.getElementById('content' ).value))"/>
liminlimin 2008-02-29
  • 打赏
  • 举报
回复
index2.php?option=content&task=showcategory&fun=show是个变量怎么就报错?
TNT_1st_excellence 2008-02-29
  • 打赏
  • 举报
回复

var text = 'index2.php?option=content&task=showcategory&fun=show';
var reg = /& *task *=.*&/ig;
var result = text.match(reg)[0];
result = result.slice(result.indexOf('=') + 1, -1);//result即為樓主要的值了
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复

var s = "index2.php?option=content&task=showcategory&fun=show";
function getValue(key){
return s.match(new RegExp(key+'=(\\w+)&'))[1];
}
alert(getValue('task'));
liuhongxing1908901 2008-02-29
  • 打赏
  • 举报
回复

var s = "index2.php?option=content&task=showcategory&fun=show";
function getValue(key){
var a = s.split(/\?|=|&/);
for(var i=0,len=a.length;i<len;i++)if(a[i]==key)return a[i+1];
return null;
}
alert(getValue('task'));

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧