0

i am using the following method to get parameter by name:

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, " "));
}

and i was wondering how to change it to get parameter that contains some string for example, i want to get the parameter that contains the word "document" but the whole parameter name is not "document".

please advise, thanks.

VisioN
  • 143,310
  • 32
  • 282
  • 281
Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498

2 Answers2

1

Like this?

 val = location.search.match(/document.*?=([^&]*)/)[1]

Although I'd rather use a function that converts the whole query string into an object (like this one) and simply apply a filter afterwards:

params = urlParams()
ks = Object.keys(params).filter(function(k) { return k.indexOf("document") >= 0 })
if(ks)
   value = params[ks[0]];

This way you can easily support multiple params (as in document1=foo&document2=bar) and avoid ugly dynamic regexp construction.

In older browsers you can use this instead of Object.keys/filter:

ks = []
for(var k in params)
     if(k.indexOf("document") >= 0)
        ks.push(k);
Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
  • i have var called urlParams that contains array of params as in the link you posted and when i tried the following code: `ks = Object.keys(urlParams).filter(function(k) { return k.indexOf("DocumentType") >= 0 })` i got the error ` Object doesn't support property or method 'keys' ` – Mahmoud Saleh Jul 23 '13 at 10:03
  • @MahmoudSaleh: `Object.keys` is IE9+, for older IE's use `for..in` or a shim. – georg Jul 23 '13 at 10:28
  • found solution for my issue here http://stackoverflow.com/questions/8306294/script438-object-doesnt-support-property-or-method-keys-for-ie – Mahmoud Saleh Jul 23 '13 at 10:30
  • filter also is not supported in IE<9, can you please edit the answer to mention that it works for IE >=9 and if possible add solution for older version. – Mahmoud Saleh Jul 23 '13 at 10:33
1

Suggestion:

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

This however, will return only the 1st match, there might be more parameters that have a similar name. You could return an array of key-value pairs for all matches.

marsze
  • 15,079
  • 5
  • 45
  • 61