Reputation: 5271
How to select the first dash -
only and before the space?
HEllo Good - That is my - first world
The regex I wrote .+?(?=-)
selected HEllo Good - That is my
.
If I have only the string HEllo Good - That is my
, it looks ok, but with the space.
var string = 'HEllo Good - That is my - first world';
console.log(string.match(/.+?(?=-)/gm));
Upvotes: 0
Views: 270
Reputation: 975
If you need the first dash only, just match the string using the beginning of input ^
:
const text = 'HEllo Good - That is my - first world';
const pattern = /^.*?\s(-)/;
const match = text.match(pattern);
console.log(`full match: ${match[0]}`);
console.log(`dash only: ${match[1]}`)
If you need what's before, including/excluding the first dash:
const text = 'HEllo Good - That is my - first world';
const patternIncludeDash = /(^.*?\s-)/;
const patternExcludeDash = /(^.*?\s)-/;
console.log('before the dash, but include dash: ' + text.match(patternIncludeDash)[1]);
console.log('before the dash, but exclude dash: ' + text.match(patternExcludeDash)[1]);
Upvotes: 2