0

So I have a code that works fine on other browsers but it doesn't work on iPhones and Safari browser. When I debug it says "Invalid regular expression: nothing to repeat" for the following code.

  function getURLParameter(a) {
    a = (new RegExp("[?|&]" + a + "=([^&;]+?)(&|#|;|$)")).exec(location.search);
    if (null == a) return null;
    a = a[1];
    a = a.replace(/+/g, "%20");
    return decodeURIComponent(a)
}

Any help you can provide would be greatly appreciated.

Berglund
  • 636
  • 2
  • 7
  • 20
  • 1
    does parameter `a` contains something like backslash? any input example for the parameter `a` would be appreciated. – Bagus Tesa Oct 09 '19 at 03:00
  • Hi, no it doesn't. The console says there is an error on a = a.replace(/+/g, "%20"); line. – Berglund Oct 09 '19 at 03:05
  • 2
    For what it's worth, there are [plenty of well-documented methods](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) for getting URL parameters in JavaScript, including the native [`searchParams.get()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get). – Tyler Roper Oct 09 '19 at 03:05

1 Answers1

4

Your problem come from a = a.replace(/+/g, "%20");, the + means repeat a character one or more times, but there's no character before it, if you want to replace "+" by "%20" you can simply call a.replace("+", "%20") or regex ver a.replace(/\+/g, "%20")

i'm sorry, a.replace("+", "%20") only replace the first "+", so you need a.replace(/\+/g, "%20") to replace all "+" by "%20"

Sou
  • 143
  • 8
  • 3
    This is correct; to elaborate, the `+` character has special meaning in regex. To treat it as the character `"+"`, you need to escape it using a backslash: `\+`. This is why the regex becomes `/\+/g`. – Tyler Roper Oct 09 '19 at 03:08
  • Hi, thanks for clarifying. I just tried it and still the issue remains. :( Strange thing is that it only occurs on safari and apple iphones. – Berglund Oct 09 '19 at 03:18
  • 1
    you used `a.replace(/\+/g, "%20")` and the issue still remains? maybe the browser cached, make sure you cleared the caches – Sou Oct 09 '19 at 03:20
  • Sorry for the hassle. You were right! It was the cache. Tyvm! – Berglund Oct 09 '19 at 03:30