Reputation: 27852
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
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
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