Run details:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36
Chrome 118
Windows
Desktop
one month ago
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
Script Preparation code:
AخA
 
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;
Tests:
  • Option 1 (Lookarounds)

     
    testString.replace(regex1, "—");
  • Option 2 (Simple Lookaround)

     
    testString.replace(regex2, "—");
  • Option 3 (Clever)

     
    testString.replace(regex3, "$1—");
  • Option 4 (Two-Pass)

     
    testString.replace(regex4step1, " – ").replace(regex4step2, "—");
  • Option 5 (Normal)

     
    testString.replace(regex5, "—");
  • Option 6 (I Am Dumb)

     
    testString.replace(regex6, "—");