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
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
You're escaping the d
after the \
in str
. You need to escape the \
in str
:
const str = 'demo1\\demo2';
console.log(str.split('\\'));
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("\\")
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.