Test name | Executions per second |
---|---|
Option 1 (Lookarounds) | 550778.1 Ops/sec |
Option 2 (Clever) | 475142.7 Ops/sec |
Option 3 (Capture Groups) | 694884.3 Ops/sec |
Option 3 (Capture Groups - Callback) | 228423.3 Ops/sec |
Option 4 (Two-Pass) | 393170.9 Ops/sec |
Option 5 (Normal) | 227873.6 Ops/sec |
const testString = "This – is – a –test –string – with – multiple – instances– of–the – pattern – and – some – variations – like–this –and this– ";
const regex1 = /(?<= )–(?= )|(?<! )– (?! )| –(?<! ) ?/g;
const regex2 = / (?=–)–? ?|– /g;
const regex3 = /(?<= )–(?! )|–(?= )|(?<! )– (?! )/g;
const regex4step1 = / +– +/g; // Remove cases with spaces on both sides
const regex4step2 = / +–|– +/g; // Remove extra spaces
const regex5 = / – | –|– /g;
const regex6 = / – ?|– /g;
testString.replace(regex1, "—");
testString.replace(regex2, "—");
testString.replace(regex3, "$1—");
testString.replace(regex4step1, " – ").replace(regex4step2, "—");
testString.replace(regex5, "—");
testString.replace(regex6, "—");