Get string value after a backslash (\) in JavaScript

Viewed 222

I know this question has been asked numerous times on this platform but I am unable to understand how to perform a split on backslash character (\) with the string below.

student\boy

I tried to split by \ but it gives undefined.

function getSecondPart(str) {
    return str.split("\\")[1];
}
console.log(getSecondPart("student\boy"));

I see that it's considering \b (backspace) so if I specify str.split("\b")[1], it gives oy but I need substring as boy.

1 Answers

Your backslash in the string is not considered as a backslash but as a special character "\b". If you want to use a backslash in a string, you need to use a double backslash.

"student\\boy" // will return "student\boy"
getSecondPart("student\\boy") // will return "boy"
Related