简体   繁体   English

使用javascript分割字符串str.split(“ \\\\”)

[英]Split string str.split(“\\”) using javascript

i have a string "demo1\\demo2". 我有一个字符串“ 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 我需要在console.log中进行demo2

You're escaping the d after the \\ in str . 您在str\\之后转义了d You need to escape the \\ in str : 您需要在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. 就像@SimpleJ已经回答一样,您需要转义反斜杠,这样才不会将其转义为下一个字符。 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: 如果您只需要'demo2'并且知道它具有什么字符,则可以执行以下操作:

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

or similar. 或类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM