Select first dash only with regex in JavaScript

Multi tool use
Select first dash only with regex in JavaScript
How to select the first dash -
only and before the space?
-
HEllo Good - That is my - first world
HEllo Good - That is my - first world
The regex I wrote .+?(?=-)
selected HEllo Good - That is my
.
.+?(?=-)
HEllo Good - That is my
If I have only the string HEllo Good - That is my
, it looks ok, but with the space.
HEllo Good - That is my
var string = 'HEllo Good - That is my - first world';
console.log(string.match(/.+?(?=-)/gm));
Your title and your question ask different things ("everything before first dash" vs. "first dash only").
– T.J. Crowder
Jun 30 at 8:30
1 Answer
1
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]);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
please add the wanted result as well.
– Nina Scholz
Jun 30 at 8:30