Courtney Thurston
Courtney Thurston

Reputation: 143

Get a portion of a string using a keyword regex in TypeScript

I have the following regex:

{thing:([^}]*)}

This matches '{thing:' and '}' exactly, and allows anything !} in the middle.

In C#, I was able to grab only the stuff in the middle with the following:

regex.Matches(stringToCheckForMatches).Cast<Match>().Select(x => x.Groups[1].Value);

Is there an equivalent way to grab that middle stuff in TypeScript? Note also that stringToCheckForMatches can contain multiple instances of the {thing:} keyword (with any middle-stuff content).

For instance, I would want this:

'fooBar/{thing:hi}{thing:hello}'

To return (in an array/list preferably) just this:

hi
hello

Alternatively, if you cannot access .match captures in TypeScript (I am honestly not sure), is there a way to change the regex to something that captures only content after '{thing:' and before '}'? That would also work.

Upvotes: 1

Views: 178

Answers (1)

Slai
Slai

Reputation: 22876

Splitting by the regular expression results in ["fooBar/", "hi", "", "hello", ""] :

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/) );

and filter can be used to get the odd elements:

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/{thing:([^}]*)}/).filter((_, i) => i & 1) );

or

console.log( 'fooBar/{thing:hi}{thing:hello}'.split(/.*?{thing:(.*?)}.*?/).filter(Boolean) );


Alternative without regular expression:

var str = 'fooBar/{thing:hi}{thing:hello}'

console.log( str.split('{thing:').slice(1).map(s => s.split('}')[0]) );

Upvotes: 1

Related Questions