2

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.

nehacharya
  • 925
  • 1
  • 11
  • 31
  • You need 2 backslashes in the string literal. Type `"student\boy"` in the browser's console to check: [How can I use backslashes (\) in a string?](https://stackoverflow.com/questions/10041998) – adiga May 06 '20 at 06:50
  • Does this answer your question? [How can I use backslashes (\‌) in a string?](https://stackoverflow.com/questions/10041998/how-can-i-use-backslashes-in-a-string) – gaganshera May 06 '20 at 07:16
  • @adiga I understand that I need two backslashes but as this data is coming from the back-end, the only way I can manipulate the string is by inserting extra backslash character through code rather than manually adding in the extra backslash for every string that's coming via the endpoint, if that makes sense. I'd really appreciate some help on how this can be achieved through regex or string functions. I have updated my question. – nehacharya May 06 '20 at 18:33

1 Answers1

2

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"
Dony
  • 1,543
  • 2
  • 10
  • 25