0

I have the following string

name=cvbb&source=Mamma+Mia&startdate=2014-03-24

How can I match the value associated with name with regular expressions, namely the string "cvbb"

/[^name]=[^&]/ matches =cvbb but i want only cvbb

Anon
  • 845
  • 5
  • 30
  • 50

3 Answers3

0

It looks like you want to get URL parameter value? In this case you could use this function :

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var value = getParameterByName('startdate');

That would put 2014-03-24 in a var named value

SauriolJf
  • 412
  • 2
  • 10
  • I was looking for it (I took the code from a project I did but I wasn't finding the original source, thank you ! – SauriolJf Apr 22 '14 at 13:29
0

I am assuming you want to select the name out, right? For that you can use the expression:-

/name=([\w]+)&source=.*/

Explanation: The first word name is written right there. After that ([\w]+) will match a list of alphanumeric characters. Then & will come and stop our selection. If you want to check that the string starts with name then use

/^name=([\w]+)&source=.*/

Caution: Using [^name] means that the characters should not be n,a,m or e which is not what you want to check. I hope this helps.

Mohit Kumar
  • 53
  • 1
  • 8
0

try

var queryString = 'name=cvbb&source=Mamma+Mia&startdate=2014-03-24';
var theStringImAfter = queryString.match(/[?&]name=([^&]*)/i)[1]

Note that queryString can be a full url e.g. from window.location.href, you don't need to parse the query string first.

If you are passing an encoded string (which is the norm if you are including characters not supported in a url such as a space, ampersand or equal sign etc.) you will want to decode the string before you use it. This can be done with decodeURIComponent(theStringImAfter).

Here is the same approach wrapped up in a reusable function

function getArg(url, arg){
    var v=url.match(new RegExp('[?&]' + arg + '=([^&]*)', 'i'));
    return (v)?decodeURIComponent(v[1]):'';
}

Usage:

var theStringImAfter = getArg('name=cvbb&source=Mamma+Mia&startdate=2014-03-24', 'name');
Jack Allan
  • 14,554
  • 11
  • 45
  • 57