Skip to content Skip to sidebar Skip to footer

Regex Not Returning Expected Value

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

Solution 1:

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:\fakepath\extra\random.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.

Solution 2:

[^\\]* match a single character not present in the list.

Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed

The problem is not with the RegEx, it's with the string itself. In JavaScript strings \ is used to escape the following character. To use backslash in the string then escape them by preceding backslash.

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

Post a Comment for "Regex Not Returning Expected Value"