0

Have an URL of type:

https://example.com/some/text/1,2,3,5

Need to replace the 1,2,3,5 part with some different parameters like 2,4,6.

Can do it in code by saving the first part of the URL example.com/some/text/ in the data property but that seems messy so. I'd like to do it through REGeX or via similar method so that don't have to save partial URL anywhere.

3
  • 1
    If the first part of the url is known, then you could do window.location.href.slice(0, endOfConstantTextPosition) + variableOfNewStuff Commented Oct 12, 2018 at 21:59
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 12, 2018 at 22:00
  • Thanks guys, this seems pretty much it. I'll get back to it in half an hour and try it out. Feel free to leave answers to get some points there too. Commented Oct 12, 2018 at 22:06

2 Answers 2

2

You could substring it to replace it, or you could break the url apart, get rid of the end, add the new ending, and then join it back up.

var test0 = 'https://example.com/some/text/1,2,3,5';
console.log( test0.slice( 0, test0.lastIndexOf( '/text/' ) + 6 ) + '2,4,6' );



var test = 'https://example.com/some/text/1,2,3,5';
//get rid of the "1,2,3,5"
var tokens = test.split( '/' ).slice( 0, -1 );
//add the new ending
tokens.push( '2,4,6' );

console.log( tokens.join( '/' ) );

Sign up to request clarification or add additional context in comments.

Comments

0

Following the @Joshua Moore's link I ended up doing this:

var oldUrl = 'https://example.com/some/text/1,2,3,5';
var newParameters = '2,4,6';
var newUrl = oldUrl.substr(0, oldUrl.lastIndexOf('/')+1) + newParameters; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.