Home > OS >  Regex not working in javascript split method but working Online test websites
Regex not working in javascript split method but working Online test websites

Time:08-18

i have this Regex (?=(?:(?:[^']*'){2})*[^']*$)\\\\n working on online test website perfectly but not in Below code. i have a string with multiple \n and also some with in " double Quotation but i want to ignore all \n with in " double Quotes.

let input = "a,b,c\n'aa\nbb\ncc'\nhello world";
    
    const lines = input.split("(?=(?:(?:[^']*'){2})*[^']*$)\\\\n");
    console.log(lines); 

i am getting this output enter image description here

want this Output:

[0]: "a,b,c"
    [1]: "aa\nbb\ncc"
    [2]: "hello world"

CodePudding user response:

Why so complicated?

let input = "a,b,c \n 'aa\nbb\ncc' \n hello world";
console.log(input.split(' \n '))

CodePudding user response:

There was some ambiguity between your explanation and your sample data. You were talking about double quotes as a delimiter in your input, but it was the opposite in the sample. There were also too many escape characters before the \n in the regex. \\\\n becomes \n. Not \\n because in a javascript string \n stands for the actual newline character. No need to esacpe it in the regex.

let input = 'a,b,c\n"aa\nbb\ncc"\nhello world';
    
let lines = input.split(/(?=(?:(?:[^"]*"){2})*[^"]*$)\n/);
console.log(lines);

  • Related