0

I have jquery regex that finds the web address URL at the top and replaces it with a new url, however the regex that I have written changes the url but regex is adding other the extra stuff from the URL at the end. It's adding 3543463456546456 at well instead of https://127.0.0.1/id=12345

<script>
 var urlTest = $(location).attr("href");
 var test1 = urlTest.replace(/https:\/\/127.0.0.1\/test1\/test2\/(12345)\/3543463456546456/g, "https://127.0.0.1/id=$1");
 $(".test").append(document.write(test1));
</script>

Not sure why its picking up 3543463456546456

Barmar
  • 596,455
  • 48
  • 393
  • 495
John
  • 19
  • 6
  • 4
    Why `document.write(test1)`?! [`.append`](https://api.jquery.com/append/) expects a string, element, or jQuery object (or array thereof, or function), but _not `undefined`_. It’s `$(".test").append(test1);`. Never use `document.write`. `document.write` is [not recommended](https://stackoverflow.com/q/802854/4642212) for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. – Sebastian Simon Feb 12 '21 at 19:19
  • Your regexp only replaces the beginning of the URL. If there's more after the matched portion it will be left in the result. – Barmar Feb 12 '21 at 19:22
  • What is the original value of `urlTest`? – Barmar Feb 12 '21 at 19:23
  • original value for urlTest is whatever the location of the url is on the web address bar. It could be https://127.0.0.1/test1/test2/12345/3543463456546456 or https://127.0.0.1/test1/test2/67890/6546456543643453 I'm wanting to capture just https://127.0.0.1/test1/test2/67890 and convert it to https://127.0.0.1/id=67890 without the extra characters at the end – John Feb 12 '21 at 19:30
  • 1
    Adding to my first comment, if `$(".test").append`, doesn’t work: is your ` – Sebastian Simon Feb 12 '21 at 19:37
  • I was able to figure it out. I added .* to the regex – John Feb 12 '21 at 20:57

0 Answers0