'JavaScript String insert newline before every occurrence of delimiter from list
In JavaScript, how do I insert a newline character before every occurrence of a delimiter from a list of delimiters?
Example:
const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) ']
const str = 'Some textC) Some textE) Some text'
I want to create the String:
Some text
C) Some text
E) Some text
Solution 1:[1]
You can solve this with a cheeky .replaceAll and simple strings instead of regex ?
const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) '];
const start = 'Some textC) Some textE) Some text';
let output = start;
for (const str of delimiters) {
output = output.replaceAll(str, "\n"+str);
}
console.log(output);
Solution 2:[2]
The first answer posted gives the simplest and best solution I believe, but here is an example of doing it with a regular expression.
const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) ']
const str = 'Some textC) Some textE) Some text';
const pattern = `(?=${delimiters.join('|').replaceAll(')', '\\)')})`;
console.log(`Pattern: "${pattern}"`);
console.log(str.replace(new RegExp(pattern, 'g'), '\n'));
Note that care should be taken to escape any characters in the delimiters that have special meaning in a regular expression.
Above, I just use .replaceAll(')', '\\)') to escape the ) after joining the delimiters with the regex alternation character | in a positive lookahead (?=alternative1|alternative2|etc) before passing it to the RegExp constructor.
Note also that this method of joining with | would not result in a reliably working regular expression if a delimiter itself contained the | character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | async await |
| Solution 2 | MikeM |
