如何从另一个字符串中提取字符

时间:2016-09-16 13:29:45

标签: javascript regex

假设有这个字符串:

http://192.168.56.101:4567/compose?p=/topic/3/werwerwerwer

我需要提取这个:

/topic/3/werwerwerwer

最后我必须获得3!有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

这应该让你以正确的方式。在调用getParam之后,您需要做的就是应用正则表达式。



/**
 * Get the value of a querystring
 * @param  {String} param The field to get the value of
 */
var getParam = function ( field, url ) {
    // this regex will match the first parameter with the given name and return
    // into the group #1 the value 
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)');
    var string = reg.exec(url);
    return string ? string[1] : null;
};

var p = getParam("p", "http://192.168.56.101:4567/compose?p=/topic/3/werwerwerwer")
if (p != null) {
   var myRegexp = /^\/\w+\/(\d+)\/.*/; // The group #1 will extract the number
   var match = myRegexp.exec(p);
   alert(match[1]); // 3
}




答案 1 :(得分:0)

当你的字符串是一个URL而p是你试图检索的参数值时,你可以这样得到它:

var string = 'http://192.168.56.101:4567/compose?p=/topic/3/werwerwerwer'
function get(name, link){
   if(name=(new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(link))
      return decodeURIComponent(name[1]);
}

var theValueOfp = get('p',string);

http://jsfiddle.net/yb4se4cz/1/