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?
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] ) });
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"); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.