日期:2014-05-16  浏览次数:20417 次

在 js中如何用正则表达式截取一段字符
http://localhost/ProgressDic.action?a=test 我要截取ProgressDic这段字符,也就是.action前的一段。正则表达式该怎么写? 

这段字符也可能是http://localhost/ProgressDic.action , 所以我想只能通过.action来判断吧。

------解决方案--------------------
JScript code

var s , re;
re = /\/([^\/]+)\.action/;
s = 'http://localhost/ProgressDic.action?a=test';
if (re.test(s)) {
    alert(RegExp.$1);
}
s = 'http://localhost/ProgressDic.action';
if (re.test(s)) {
    alert( RegExp.$1);
}

------解决方案--------------------
var reg = /^http\:\/\/[a-zA-Z0-9]+(\/[a-zA-Z0-9]+)*.action[$|\?]/;//之所以最后加入[$|\?]是为了判断结尾了,或者后面跟着?的情况
var test_value = document.getElementById('a').value;
if(reg.test(test_value)){
alert("true!"); //符合要求时,执行这个,可以在这加符合要求时的操作
var aaa = test_value.match(reg);
var bbb = aaa[0].substring(0,aaa[0].length-8);//在这个地方,把不需要的后缀去掉就可以了,如果还要去掉(.action)的话,把式子中的1换成8即可
alert(bbb);
}
else{
alert("false!");//不符合要求时,弹出错误提示,或者相应的操作
}

试试这个可以符合你的要求不!