Skip to content Skip to sidebar Skip to footer

Split By Backslash In Javascript

I'm trying to split a string '\b1\c1\d1' into ['','b1','c1','d1']; But even with string.split('\\') (and all ways that internet says) it simply give me a ['1c1d1']; How can I get t

Solution 1:

Worked for me this way.

Tested on chrome console:

var x ="\b1\c1\d1"; // results in "1c1d1"var x ="\\b1\\c1\\d1"; // results in "b1\c1\d1"var y = x.split("\");
VM160:2 Uncaught SyntaxError: Unexpected token     ILLEGAL(…)InjectedScript._evaluateOn @ VM101:875InjectedScript._evaluateAndWrap @ VM101:808InjectedScript.evaluate @ VM101:664
var y = x.split("\\");  // THIS WORKS!! ["", "b1", "c1", "d1"]

Solution 2:

The most easier way of doing is by converting the given string in raw string where we retrieve the backslash as it is

for above scenario "\b1\c1\d1" into ["","b1","c1","d1"]

let a = String.raw`YOUR_STRING`;

let b=a.split("\\");

for eg;

let a =String.raw`\b1\c1\d1`; //Output a ="\b1\c1\d1"

let b = a.split("\\"); // Output b = ["", "b1", "c1", "d1"]

Have already tested in chrome console and for more information on String.raw method please refer: this link

Solution 3:

You can split your "fictional string" if it will be a regexp object

/\b1\c1\d1/.source.split('\\');

Post a Comment for "Split By Backslash In Javascript"