1

Suppose to have this string:

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

I need to extract this:

/topic/3/werwerwerwer

At the end I must obtain 3! Anyone can help me?

2
  • 7
    post your attempts.. Commented Sep 16, 2016 at 13:30
  • Will the structure of the string always be the same? i.e. Same slashes and all. If so you could do an ugly string search targeting the / but it may not be very reusable or modular. Look into yourStr.split('/') as well as parseInt(), these may be of usable value. Commented Sep 16, 2016 at 13:37

2 Answers 2

1

This should put your in the right way. After calling getParam, all you need to do is apply the regular expression.

/**
 * 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
}

Sign up to request clarification or add additional context in comments.

Comments

0

When your string is an URL and p is the parameter value you try to retrieve you can get it like this:

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.