How To Insert A Backslash In A String Using Regex Or String Functions To Extract Substrings After \ In JavaScript?

I have the following strings:


I want to extract the substring after the \ i.e., boy, class, playground, teacher, subject. Also, school remains a constant substring for all strings.

I know the solution is to add in an extra backslash like school\\boy, school\\teacher etc. since it's treating \b,\t as one special character, but the above data is coming from the back-end service so the solution to add the extra backslash manually for every string is not feasible.

My question is how can I insert this extra \ backslash through string functions or regex and extract the substrings after the \?

I tried doing this:

var str = "school\boy";
var newstr = str.slice(0,6) + '\\' + str.slice(6); \\ newstr = school\\boy

but it gives undefined. If I do a split by a single backslash, it gives output as \boy which is incorrect. I don't understand why the split doesn't work. It's still treating \b as a special character even after adding the extra \ after character 'l' in the string.



I'm assuming your back-end is generating the JavaScript code (with only one backslash). The best thing to do is to reconfigure your back-end.

You can also use fetch() to perform a GET request to obtain the string, which won't need escaping.

However, if for some reason, you can't do that, you can use String.raw():

const str = String.raw `school\boy`; // Yes, without parenthesis.

But if you use String.raw(), make sure there's something after the backslhash, as \` will not terminate the string!