Test name | Executions per second |
---|---|
Option 1 (Lookarounds) | 548631.0 Ops/sec |
Option 2 (Simple Lookaround) | 953050.9 Ops/sec |
Option 3 (Clever) | 481046.8 Ops/sec |
Option 4 (Two-Pass) | 401504.5 Ops/sec |
Option 5 (Normal) | 1029438.0 Ops/sec |
Option 6 (I Am Dumb) | 1010524.4 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, "—");