0

I have a URL:

http://test.com/backgrounds/testimage.jpg

and I need to insert a 't_' at the beginning of the filename resulting in:

http://test.com/backgrounds/t_testimage.jpg

What would be the simplest way to do this in jQuery? Thanks for any help :)

2 Answers 2

2

Use a regex replacement to look for the last "/" and replace it with "/t_". Difficult to read with the escapes but:

"http://test.com/backgrounds/testimage.jpg".replace(/\/([^\/]*)$/, "/t_$1");

Swap out the string with whatever other string or variable you want to operate on. Alternately use something to parse the URL if you want more control or just prefer more readability.

Or alternately you could also remove the "/" from the pattern and the substitution. I was hoping JS had a non-regex replaceLast but that doesn't seem to be the case.

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

Comments

1

Don't even need jQuery...

var derp = 'http://test.com/backgrounds/testimage.jpg';
var split_derp = derp.splitOnLast('/');
var new_derp = split_derp[0] + '/t_' + split_derp[1].slice(1);

There's got to be a more compact/faster way, but that should work, I think.

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.