i'm struggling figure out a regex. I want to replace a space with a dash but only if the following word matches either class
or series
.
I have tried the following:
/\s(?=[^\s]*(class|series)$)/gi
' E-Class' => ' -E-Class'
'E Class' => 'E-Class'
' E Class' => ' E-Class'
Above is close, but if there is already a dash it puts one before, which it shouldn't.
Following regex/approach matches the criteria described by the OP ...
/\s(?=class|series)|\s(\w+-?)+(?=class|series)/gi
.
Actually it's two separate regular expressions, one (\s(?=class|series)
) for the obviously simple case of matching the pattern of e.g. ' E Class'
, the other one (\s(\w+-?)+(?=class|series)
) for the more complex patterns such as e.g. ' E-Class'
or ' Ee-ef-fooSeries'
where the OP wants to "... replace a space with a dash but only if the following word [contains] either class
or series
" (contains and not matches; see my first comment above).
The regex' match result needs to be handled by a custom replacer function. A test case might look similar to the next provided one ...
const testEntries = [
// OP's request.
[' E-Class', ' -E-Class'],
['E Class', 'E-Class'],
[' E Class', ' E-Class'],
// Bonus test.
[' Ee-eClass', ' -Ee-eClass'],
[' Ee-ef-Class', '-Ee-ef-Class'],
[' Ee-ef-fooSeries', ' -Ee-ef-fooSeries'],
];
const regX = (/\s(?=class|series)|\s(\w+-?)+(?=class|series)/gi);
function didPassTest([value, expectedValue]) {
return (
value.replace(regX, (match) =>
'-' + match.trim()
) === expectedValue
);
}
console.log(
'testEntries.every(didPassTest) ?..',
testEntries.every(didPassTest)
);
One can unify the above OR
based regex literal into a version which matches the overall pattern while capturing the word ...
/\s((?:\w+-?)*(?:class|series))/gi
The above example code then changes to ...
const testEntries = [
// OP's request.
[' E-Class', ' -E-Class'],
['E Class', 'E-Class'],
[' E Class', ' E-Class'],
// Bonus test.
[' Ee-eClass', ' -Ee-eClass'],
[' Ee-ef-Class', '-Ee-ef-Class'],
[' Ee-ef-fooSeries', ' -Ee-ef-fooSeries'],
];
const regX = (/\s((?:\w+-?)*(?:class|series))/gi);
function didPassTest([value, expectedValue]) {
return (value.replace(
regX, (match, word) => '-' + word
) === expectedValue);
}
console.log(
'testEntries.every(didPassTest) ?..',
testEntries.every(didPassTest)
);
I believe you should only match the space before class or series and not every space before so you can try something like this :
/\s(class|series)$/gi
Managed to figure it out, this works as expected:
/\s(?=class|series)/gi