0

I have a bunch of strings and need to return substrings from them

The output should replace occurrences of

Test: intervening text - Exists

with

intervening text

I've tried:

const inputs = [
  'Test: Text - N GTTTsds - Exists',
  'Test: Text something here - Exists',
  'Tictactoe foo baz - bar - Exists',
  'Something still here',
  'Joe Doe'
];
const output = [];

inputs.forEach(input => {
  const resp = /(?:Test: )?(.+)(- Exists)?/.exec(input);
  output.push(resp);
});
console.log(output);

but it doesn't produce the expected output of:

[
    "Text - N GTTTsds", 
    "Text something here", 
    "Tictactoe foo baz - bar"
    'Something still here',
    'Joe Doe'
]
2
  • I made you a snippet Commented Jan 7, 2020 at 19:06
  • The second input string only contains Exist (without the s at the end). Was that intentional? Commented Jan 7, 2020 at 19:08

4 Answers 4

1

Why not just replace them?

const inputs = [
 'Test: Text - N GTTTsds - Exists',
 'Test: Text something here - Exist',
 'Tictactoe foo baz - bar - Exists',
 'Something still here',
 'Joe Doe'
];
const output = inputs.map(input => input.replace(/(^Test:)|(- Exist(s?)$)/g, '').trim());

console.log(output);

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

Comments

0

You may use this regex with anchors and lazy quantifier:

/^(?:Test: )?(.+?)(?: - Exists?)?$/;

Also you need to grab first capture group from resulting array.

const inputs = [
 'Test: Text - N GTTTsds - Exists',
 'Test: Text something here - Exist',
 'Tictactoe foo baz - bar - Exists',
 'Something still here',
 'Joe Doe'
];
const output = [];
const re = /^(?:Test: )?(.+?)(?: - Exists?)?$/;
var resp;

inputs.forEach(input => {
 resp = re.exec(input);
 if (resp != null && resp.length > 1)
  output.push(resp[1]);
});

console.log(output);

Comments

0

You can remove Test in one iteration and - Exists in another.

const input = [
 'Test: Text - N GTTTsds - Exists',
 'Test: Text something here - Exist',
 'Tictactoe foo baz - bar - Exists',
 'Something still here',
 'Joe Doe'
];

const output = input.map(s => s.replace(/Test:\s+/g, '').replace(/\ -\ Exists?/g,  ''));

console.log(output);

Comments

0

Other solution: Force the Regex to match the start and the end of each string (^ and $) and make the quantifier for arbitrary characters in the middle lazy by appending an ?.

const inputs = [
  'Test: Text - N GTTTsds - Exists',
  'Test: Text something here - Exist',
  'Tictactoe foo baz - bar - Exists',
  'Something still here',
  'Joe Doe'
];
const output = [];

inputs.forEach(input => {
  const resp = /^(?:Test: )?(.+?)(- Exists)?$/.exec(input);
  output.push(resp);
});
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.