-1

The url being replaced looks like this:

/profile/something/

with something being dynamic but profile should always be in the url. I tried '/\w+/g' as the first argument in replace(), but it did this instead:

/hello123/hello123/ 

instead of:

/profile/hello123/

Does anyone know how I can use the replace() only after a certain index of the url string? Or maybe replace every character except the first instance of profile?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • There is no `replace` function in jQuery. Perhaps you're talking about the [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function in JavaScript? There are many questions about replacing parts of the URL. Perhaps http://stackoverflow.com/q/30457053/215552? – Heretic Monkey Jan 30 '17 at 22:09
  • you can use `string.slice(x)` where `x` is the number of characters you wish to skip – Adjit Jan 30 '17 at 22:09
  • Or http://stackoverflow.com/q/4025635/215552 – Heretic Monkey Jan 30 '17 at 22:10
  • Thanks guys string.slice(x) works perfect. – Zorgan Jan 30 '17 at 22:16

1 Answers1

0

Solved by @Adjit - str.slice(x) works well here and is the most simple.

new = $('#view_posts').attr('href').slice(9);

$('#view_posts').attr('href', $('#view_posts').attr('href').replace(new, data.username));

or

new = $('#view_posts').attr('href').slice(0, 9);

$('#view_posts').attr('href', new + data.username);
Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • This will replace the terminating slash, as well. It's just grabbing everything after 9 characters and replacing it, which seems very inefficient. Instead you could `slice(0,9)` and append to that with no replace needed. – Jon Uleis Jan 30 '17 at 22:32
  • True that does seem better, i've changed it to my 2nd edit. Thanks. – Zorgan Jan 30 '17 at 22:46