0

How can we split the following tag to extract the substring "PDSGJ:IO.HJ".

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. I need '\' also because I need to further split and get the value.

Any other method is there to get the value?

user1400915
  • 1,933
  • 6
  • 29
  • 55
  • this might be worth a read :) https://stackoverflow.com/questions/4607745/split-string-only-on-first-instance-of-specified-character#4607799 – treyBake Aug 22 '17 at 10:14
  • I think `\\initvalues\PDSGJ:IO.HJ~some` is getting changed to `\initvaluesPDSGJ:IO.HJ~some` as you are not escaping the `\\`. Try after escaping it, it should work. – Hassan Imam Aug 22 '17 at 10:21
  • 1
    to have your code working, you should escape your "\" when you set your test string: `input = "\\\\initvalues\\PDSGJ:IO.HJ~some"`. When the string comes with this value it is ok, but when entering it literally, you have to escape them – Kaddath Aug 22 '17 at 10:21
  • Like as pointed out you need to escape the '\' to '\\',.. also after doing this your going to get `["", "", "initvalues", "PDSGJ:IO.HJ~some"]`, so you will also want `alert(b[3])` for your `PDSGJ:IO.HJ~some ` – Keith Aug 22 '17 at 10:24
  • `var input = "\\initvalues\PDSGJ:IO.HJ~some";` now when you do :- `console.log(input);` it will show you `\initvaluesPDSGJ:IO.HJ~some` – Alive to die - Anant Aug 22 '17 at 10:25
  • Yosvel's answer has been accepted because , it doesnt target on changing the input format . Input remains as it is . – user1400915 Aug 23 '17 at 05:22

3 Answers3

1

You can use regular expressions:

var input = '\\initvalues\PDSGJ:IO.HJ~some',
    b = input.match(/[A-Z]+:[A-Z]+.[A-Z]+~[a-z]+/);
  
console.log(b && b[0]);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
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);
Manuel Otto
  • 6,410
  • 1
  • 18
  • 25
0

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"]
Jonas Libbrecht
  • 768
  • 1
  • 8
  • 17