0

What's the problem with this?

the hash is : #/search=hello/somethingelse/

window.location.hash.replace(/search=([^\/]*)/gi, "search=" + value);

EDIT:

I want to change just a specific part of the hash not the whole hash.

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213

3 Answers3

5

hash.replace() does not actually change the hash, only return a value (as it is a String function). Try assigning that result, using:

window.location.hash = window.location.hash.replace(/search=([^\/]*)/gi, "search=" + value);

On the other hand, window.location.replace() is actually a function that changes the URL, but that does not work directly with regexes.

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
1

Did you forget to assign it?

replace() is a String function and returns a new String object, it doesn't modify the original String.

window.location.hash = window.location.hash.replace(/search=([^\/]*)/gi, "search=" + value);
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
0

JavaScript strings are immutable, I believe. (a quick Google search shows that both SO and Wikipedia back me up)

This effectively means their value can't be changed without an assignment statement.

Hence, String.replace(...) doesn't change the String's value, but instead returns a new String.

var replaced = window.location.hash.replace(/search=([^\/]*)/gi, "search=" + value);

Now, since you are presumably trying to change the window.location.hash you're probably fishing for...

window.location.hash = window.location.hash.replace(/search=([^\/]*)/gi, "search=" + value);
Community
  • 1
  • 1
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119