Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Capture value out of query string with regex?

I am trying to select just what comes after name= and before the & in :

"/pages/new?name=J&return_url=/page/new"

So far I have..

^name=(.*?).

I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.

The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

/name=([^&]*)/

  • remove the ^ and end with an &

Example:

var str     = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);

The better way is to break all the params down (Example using current address):

function getParams (str) {
   var queryString = str || window.location.search || '';
   var keyValPairs = [];
   var params      = {};
   queryString     = queryString.replace(/.*??/,"");

   if (queryString.length)
   {
      keyValPairs = queryString.split('&');
      for (pairNum in keyValPairs)
      {
         var key = keyValPairs[pairNum].split('=')[0];
         if (!key.length) continue;
         if (typeof params[key] === 'undefined')
         params[key] = [];
         params[key].push(keyValPairs[pairNum].split('=')[1]);
      }
   }
   return params;
}


var url    = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];

Update

Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...