1

I have a string something like this:

http://stackoverflow.com/questions/ask

And would like to return this part:

http://stackoverflow.com/questions/

How can I do this using pure javascript? Thanks!

3 Answers 3

1

This will match and remove the last part of a string after the slash.

url = "http://stackoverflow.com/questions/ask"
base = url.replace(/[^/]*$/, "")
document.write(base)

Help from: http://www.regexr.com/

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

1 Comment

I don't think he wanted to remove the trailing slash
0

For slicing off last part:

var test = 'http://stackoverflow.com/questions/ask';
var last = test.lastIndexOf('/');
var result = test.substr(0, last+1);

document.write(result);

Comments

0

You can accomplish this with the .replace() method on String objects. For example:

//Regex way
var x = "http://stackoverflow.com/questions/ask";
x = x.replace(/ask/, "");

//String way
x = x.replace('ask', "");

//x is now equal to the string "http://stackoverflow.com/questions/"

The replace method takes two parameters. The first is what to replace, which can either be a string or regex, literal or variable, and the second parameter is what to replace it with.

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.