Reputation: 424
Having the next string
{ Hello, testing, hi stack overflow, how is it going }
Match every word inside of curly brackets without the comma.
I tried this:
\{(.*)\}
which take all, commas and brackets included.
\{\w+\}
I thought this will work for words but it wont, why?
Tried this but I got null, why?
str = "{ Hello, testing, hi stack overflow, how is it going }";
str2 = str.match("\{(.*?)\}")[1]; // Taking the second group
console.log(str2);
console.log(str2.match("/w+"));
Upvotes: 0
Views: 126
Reputation: 59
Perhaps slightly complex, but this one line makes a string into an array of the words in the string.
str = str.replace(/^\{([^}]*)\}$, "$1"/).split(/[\W]/).filter(x => x);
// ^ -- string start
// \{ -- find {
// ([^}]*) -- match zero or more characters not between [^ and ]
// \} -- find }
// $ -- string end
// split(/[\W]/) removes anything not 0-9 a-z A-Z and underscore
// filter(x => x) removes empty strings from the array
To get the result as a string, use this instead.
str.replace(/[{},]+/g, "").replace(/(^\s+)|(\s$)/g, "")
// /[{},]+/g -- remove all instances of "{", "}", and ","
// /(^\s+)|(\s$)/g -- remove leading and trailing whitespace
Upvotes: 0
Reputation: 3248
did you try:
first get everything between {} by using
\{(.*?)\}
then get all words inside of the resulting string.
\w+
Here is an explanation:
\w+ matches any word character (equal to [a-zA-Z0-9_])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed
Upvotes: 1