Regex not returning expected value [closed]

I have a basic regex that should return string after the last backslash .

Regex :

/([^\]*$)/

Works fine in Regex101.

Output :

random.html

But not in Javascript example bellow :

console.log("C:fakepathextrarandom.html".match(/([^\]*$)/));

Output :

[“C:akepathextra andom.html”, “C:akepathextra andom.html”, index: 0, input: “C:akepathextra andom.html”]

Answer

The problem is not with the RegEx, it’s with the string itself. In JavaScript strings is used to escape the following character.

The string

"C:fakepathextrarandom.html"

is after escaping

C:akepathextra
andom.html

To use backslash in the string, escape them by preceding backslash.

"C:\fakepath\extra\random.html"

console.log("C:\fakepath\extra\random.html".match(/[^\]*$/));

To get the text after last , use String#split and Array#pop

"C:\fakepath\extra\random.html".split('\').pop() // random.html
                                          ^^ Note: this backslash also need to be escaped.

Leave a Reply

Your email address will not be published. Required fields are marked *