user1775888 user1775888 - 1 month ago 12
Javascript Question

get any string between last two slash or other last two same character with regex?

how to get any string between last two slash or other last two same character in javascript?

use regex not split there's several similar question in so but I only can find answer is use split ...

my regex pattern in below, it not match do I miss something?

I was hoping the result is something like this, how to make it?

['s', index: .., input: ...]


regex

var str = '/a/b/c/s/';
var regexPattern = /([^/]*)\/$/;
str = regexPattern.exec(str);
console.log(str); // ["s/", "s"]
if (str == 's') {
console.log(true)
}


https://jsfiddle.net/30bjt5ew/

Answer

You can use this regex:

/[^/]*(?=\/$)/

it will output ["s", index: 7, input: "/a/b/c/s/"] as you expected.

[^/]* # any char that is not /
(?=\/$) # Look foward for a / and the end of string

jsfiddle

Comments