-1

I have an array of string which looks like this:

ErrStr = [
\\abc\def\ghi;  ,
\\klm\nop\qrs;
]

So, this array of strings will be dynamic, so what I want to extract is only the abc and klm from this array.

This piece of code is what joins the strings after filtering from the data:

let errorArr = filteredError.map(a => a.ErrStr.split('\\\\', '')).join('')

I tried the above code, it cuts the \\ and replaces with , but I am not able to figure out how do I remove the 2nd and 3rd part of the string. Thanks in advance.

pranami
  • 1,381
  • 5
  • 22
  • 43

1 Answers1

0

Backslash in an Escape character in Javascript and has special meaning. To literally use it you need to, well, escape it beforehand with another backslash

const str1 = "\a";
console.log(str1);  // "a"    Where's my backslash?
const str2 = "\\a";
console.log(str2);  // "\a"   Aha, here it is

Therefore, first make sure your array has Strings (which currently what you provided are not strings therefore it's an invalid JSON)

And use:

const arr = [
  "\\\\abc\\def\\ghi;",
  "\\\\klm\\nop\\qrs;",
];

const codes = arr.map(s => /(?<=^\\\\)[^\\]+/.exec(s)).flat()
console.log(codes); // ["abc", "klm"]

Overview example on Regex101.com

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Thanks for the answer. I am getting this error on `flat` : `Property 'flat' does not exist on type 'RegExpExecArray[]'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2019' or later.` Any idea what needs to be changed. I am not allowed to change any library – pranami Jul 15 '21 at 10:29
  • @pranami as far as I can see Array.prototype.flat() is supported by all major browsers. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat - The error is quite strange though, since in the code we're applying `.flat()` on an .map() mapped Array, not on regexp. Seems to me like a Typescript issue https://stackoverflow.com/questions/53556409/typescript-flatmap-flat-flatten-doesnt-exist-on-type-any – Roko C. Buljan Jul 15 '21 at 11:41