简体   繁体   English

javascript中涉及反斜杠的字符串拆分

[英]splitting of strings in javascript which involves backslash

How can we split the following tag to extract the substring "PDSGJ:IO.HJ" . 我们如何分割以下标记以提取子字符串“ PDSGJ:IO.HJ”

var input = "\\\\initvalues\\PDSGJ:IO.HJ~some" . var input = "\\\\initvalues\\PDSGJ:IO.HJ~some"

I tried the following: 我尝试了以下方法:

var input = "\\initvalues\PDSGJ:IO.HJ~some";
var b = input.split('\\');
alert(b[1]);

Note: The format remains the same , \\\\,\\, ~ format is same and mandatory for all strings . 注意:格式保持相同, \\\\,\\,〜格式相同,并且对所有字符串都是必需的。

But the problem is , I get the output as: initvaluesPDSGJ:IO.HJ~some . 但是问题是,我得到的输出为: initvaluesPDSGJ:IO.HJ〜some I need '\\' also because I need to further split and get the value. 我还需要'\\',因为我需要进一步拆分并获取值。

Any other method is there to get the value? 还有其他获取价值的方法吗?

You can use regular expressions : 您可以使用正则表达式

 var input = '\\\\initvalues\\PDSGJ:IO.HJ~some', b = input.match(/[AZ]+:[AZ]+.[AZ]+~[az]+/); console.log(b && b[0]); 

The backslash is interpreted as an escape character . 反斜杠被解释为转义字符 So you're gonna have to add another backslash for each backslash. 因此,您将必须为每个反斜杠添加另一个反斜杠。 Then directly search for the last backslash and then slice the string: 然后直接搜索最后一个反斜杠,然后对字符串进行切片:

var input = "\\\\initvalues\\PDSGJ:IO.HJ~some";
var index = input.lastIndexOf('\\');
var str = input.slice(index+1)
alert(str);

It is indeed correct, like the others already mentioned, that a backslash is interpreted as an escape character. 像已经提到的其他反斜杠一样,将反斜杠解释为转义符确实是正确的。

To output proper result, thus as a list. 输出适当的结果,因此作为列表。

var txt='\\\\initvalues\\PDSGJ:IO.HJ~some';
txt.split(/\\\\/).pop(0).split(/\\/)

(2) ["initvalues", "PDSGJ:IO.HJ~some"]

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

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