-3

I am trying to extract ?ref value from a URL and wanted to replace it with some other value.

Example Lets say my URL is something like this http://myexample.com/?ref=test?nref=xml&page=1 or it can be http://myexample.com/?fref=like?ref=test?nref=xml&page=1

From the above url I wanted to find ?ref value and wanted to replace it from another string say "testing". Any help and also wanted to learn advance Regular expressions any help.

Thanks in advance.

Soarabh
  • 2,910
  • 9
  • 39
  • 57

3 Answers3

1

A solution for your posted examples.

str = str.replace(/\b(ref=)[^&?]*/i, '$1testing');

Regular expression:

\b             the boundary between a word char (\w) and and not a word char
 (             group and capture to \1:
  ref=         'ref='
 )             end of \1
[^&?]*         any character except: '&', '?' (0 or more times)

The i modifier is used for case-insensitive matching.

See working demo

hwnd
  • 69,796
  • 4
  • 95
  • 132
0

Make sure you don't have two "?" in url.   I assume you mean http://myexample.com?ref=test&nref=xml&page=1

you can use the function below

here url is your url, name is the key, in your case it is "ref", and the new_value is the new value, i.e. the value that would replace "test"

the function will return the new url

function replaceURLParam (url, name, new_value) {

  // ? or &, name=, anything that is not &, zero or more times          
  var str_exp = "[\?&]" + name + "=[^&]{0,}";

  var reExp = new RegExp (str_exp, "");

  if (reExp.exec (url) == null) {  // parameter not found
      var q_or_a = (url.indexOf ("?") == -1) ? "?" : "&";  // ? or &, if url has ?, use &
      return url + q_or_a + name + "=" + new_value;
  }

  var found_string = reExp.exec (url) [0];

  // found_string.substring (0, 1) is ? or &
  return url.replace (reExp, found_string.substring (0, 1) + name + "=" + new_value);
}
0

Try this :

var name = 'ref', 
    value = 'testing',
    url;

url = location.href.replace(
    new RegExp('(\\?|&)(' + name + '=)[^&]*'), 
    '$1$2' + value
);

new RegExp('(\\?|&)(' + name + '=)[^&]*') gives /(\?|&)(ref=)[^&]*/ which means :

"?" or "&" then "ref=" then "everything but '&' zero or more times".

Finally, $1 holds the result of (\?|&) while $2 holds the result of (ref=).

Links to read : replace, regexp.