0

I have strings that follow this format:

/users/john, /users/anna, /users/charles/something

I want to get the users name. So, it's either the word after /users/ or the word after /users/ and before another /.

How can I do that in javascript?

3
  • You have to split from / sign then get the correct index Commented Aug 24, 2018 at 3:51
  • 1
    string.split("/")[2] will do. Commented Aug 24, 2018 at 3:53
  • 1
    @Khay But that wouldn't check if the string matches the expected format. Commented Aug 24, 2018 at 3:55

2 Answers 2

2

Match the /users/, and then capture non-slashes in a group, and extract that group:

['/users/john',
'/users/anna',
'/users/charles/something']
.forEach(str => {
  console.log(
    str.match(/\/users\/([^/]+)/)[1]
  )
});

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

2 Comments

Do you know why I might be getting this error: no-useless-escape: Unnecessary escape character: \/. in my editor?
Oops, apparently you don't have to escape forward slashes inside a character set here. Change to [^/]
0

Try using a regex replace with a capture group:

var input = 'users/charles/something';
if (/^users\/.*$/.test(input)) {
    var username = input.replace(/^users\/([^\/]+).*/, "$1");
    console.log(username);
}
else {
    console.log("no match");
}

2 Comments

Why doing a replace instead of a 'match' as CertainPerformance suggested?
@HommerSmith His performance is not certain on JavaScript questions, I wasn't sure about match.

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.