Home > Software design >  TypeScript - grab certain text from string
TypeScript - grab certain text from string

Time:07-06

I have the following text pattern:

test/something

The test/ pattern never changes, only the word that comes after it. I want to grab something, basically the word that comes after test/. However, it can also come in a sentence, for example:

Please grab the word after test/something thank you.

In this case, I want to grab something only, not the thank you.

I wrote the following code:

const start = text.indexOf('test/');
const end = text.substring(start).indexOf(' ')   start;
const result = text.substring(start, end).replace('test/', '');

This works, however only if the pattern is in a sentence with spaces. How can I overcome this for every case, even if the input string is just test/something without anything before or after it?

CodePudding user response:

I'd use a regular expression instead. Match test/, and then match and capture anything but a space, then extract that first capture group.

const text = 'Please grab the word after test/something thank you';
const word = text.match(/test\/(\S )/)?.[1];
console.log(word);

In modern environments, looking behind for the test/ will be a bit easier - no need for the capture group.

const text = 'Please grab the word after test/something thank you';
const word = text.match(/(?<=test\/)\S /)?.[0];
console.log(word);

CodePudding user response:

Use a regular expression with a positive lookbehind ((?<=...)) and perform a non-greedy capture of anything (. ?) up to the first word boundary (\b):

const extract = (s) => s.match(/(?<=test\/). ?\b/);

console.log(extract('test/something'));
console.log(extract('Please grab the word after test/something thank you.'));

  • Related