Ad

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

I have the following strings:

school\boy
school\class
school\playground
school\teacher
school\subject

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
console.log(newstr.split('\\\\')[1]);

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.

Ad

Answer

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.
console.log(str.split("\\")[1])

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

Ad
source: stackoverflow.com
Ad