Hommer Smith
Hommer Smith

Reputation: 27852

How do I get the string from bigger string in Javascript?

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?

Upvotes: 0

Views: 86

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370679

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]
  )
});

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

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");
}

Upvotes: 0

Related Questions