0

I have a string like this

const str = "'a' 'b' 'c'"

I want to split it and get in result array of strings

const arr = str.split(" ")

but in output I get:

["'a'", "'b'", "'c'"]

How can I get in output array without nested strings?

Desired result

["a", "b", "c"]

3
  • Is there a possibility that one of those strings will have escaped ' character? For example ["'doesn\'t' 'abc' 'mustn\'t'"] Commented Dec 19, 2019 at 12:48
  • 1
    Array.from(text.matchAll(/'([^']+)'/g), m => m[1]) Commented Dec 19, 2019 at 12:49
  • Or Array.from(text.matchAll(/'([^'\\]*(?:\\.[^'\\]*)*)'/gs), m => m[1]) Commented Dec 19, 2019 at 12:56

2 Answers 2

1

You could use replace method by passing a regex expression in combination with map method by passing an arrow function as argument.

const str = "'a' 'b' 'c'";
console.log(str.split(' ').map(el => el.replace(/'/g, "")));

Sign up to request clarification or add additional context in comments.

Comments

1

First remove ' from above string using .replace() and then split it:

const str = "'a' 'b' 'c'";

const output = str.replace(/'/g, '').split(' ');

console.log(output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.