Home > OS >  Javascript get lines when string has plain text escape sequence in it, like "hello\nworld"
Javascript get lines when string has plain text escape sequence in it, like "hello\nworld"

Time:12-20

Lets say I have a string like this

const str = `{FOO: "Hello\nWorld"}
{"BAR": "Nice\nTo\nMeet\nYou"}`

when I do str.split("\n") the output is

Array(6) [ "{FOO: \"Hello", "World\"}", "\"BAR\": \"Nice", "To", "Meet", "You\"}" ]

that's expected, but I want to get an output like this:

Array(2) [ '{FOO: "Hello\nWorld"}', '{"BAR": "Nice\nTo\nMeet\nYou"}' ]

CodePudding user response:

As far as the JavaScript string is concerned, there is no difference between these:

var a = `
`;
var b = `\n`;
console.log(a === b); // outputs true

So there's no way to do quite what you're describing. Was your intent to escape the escape sequences?

const str = `{FOO: "Hello\\nWorld"}
{"BAR": "Nice\\nTo\\nMeet\\nYou"}`

CodePudding user response:

You can do use Regular expression /\{[^}] \}/g:

const str = `{FOO: "Hello\nWorld"}
{"BAR": "Nice\nTo\nMeet\nYou"}`

const result = str.match(/\{[^}] \}/g)

console.log(result)

  • Related