Regex not returning expected value [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Regex not returning expected value [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.
We are here to answer your question about Regex not returning expected value [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji