0

i have a string "demo1\demo2".

var str="demo1\demo2";
console.log(str.split("\\")[1])); \\gives undefined
console.log(str.split("\")[1])); \\gives undefined

gives undefined. i need to demo2 in console.log

Ireal
  • 355
  • 4
  • 16

3 Answers3

2

You're escaping the d after the \ in str. You need to escape the \ in str:

const str = 'demo1\\demo2';
console.log(str.split('\\'));
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • 1
    my string is "demo\demo" and not "demo\\demo" – Ireal Mar 20 '17 at 17:35
  • let me rewrite the question my string is "demo1\demo2" and i need demo2 – Ireal Mar 20 '17 at 17:36
  • 1
    In order to place a backslash in a string in javascript, you have to escape it. So `"demo\\demo"` will print as `demo\demo`. If you're receiving a string with a backslash from some external source (file, api, etc), it will already have the backslashes escaped. Try running `console.log('demo\demo')` and `console.log('demo\\demo')` in your console. – SimpleJ Mar 20 '17 at 17:38
  • i'm getting "demo1\demo2" from external source and not able to split demo2 `"demo1\demo2".split("\\"); \\gives demo1demo2` – Ireal Mar 20 '17 at 18:05
  • The string `"demo1\demo2"` is actually `"demo1" + "\d" + "emo2"`. `\d` is being interpreted as an escape character (like `\n`, `\t`, `\r`). `\d` isn't a valid escape character, so the backslash is ignored. In order to actually place a backslash into your string, you must escape it with an additional backslash in the source: `"demo1\\demo2" -> demo1\demo2`. – SimpleJ Mar 20 '17 at 18:12
0

Just like @SimpleJ already answered, you need to escape your backslash so that it is not considered to be escaping the next character itself. As proof, when you don't escape your backslash with another backslash, here is how your string gets outputted (in case you haven't checked this yourself already):

> console.log('demo1\demo2')
demo1
undefined
> console.log('demo1\\demo2')
demo1\demo2
undefined
> console.log("demo1\demo2")
demo1
undefined
> console.log("demo1\\demo2") // same goes for double quoted strings
demo1\demo2
undefined

So this is the way to go:

"demo1\\demo2".split("\\")
-2

If the items inside need escaping, you could run it through something like this first.

If you just need 'demo2' and you know what characters it has, you could something like:

console.log(str.match(/[^a-z0-9A-Z]([a-z0-9A-Z]*)$/)[1]);

or similar.

Community
  • 1
  • 1
xdhmoore
  • 8,935
  • 11
  • 47
  • 90