Replace quotes

Benchmark created on


Setup

const data = [
'Предложение "Проценты "MEGA" под защитой" для компании "Рога и копыта"',
'"Просто предложение"',
'Разверни "меня"',
'"Продолжение" истории',
'Что-то там про "музыку"',
];

for (let i = 0; i < 1000; i++) {
	data.push(data[Math.floor(Math.random() * data.length)]);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Plain JS replacement
function replaceQuotes(src) {
  let result = src.replace(/\s+/, ' ').split(' ');

  return result.map(s => {
    let r = s;
    if (s.startsWith('"')) {
      s = '«' + s.slice(1);
    }
    if (s.endsWith('"')) {
      s = s.slice(0, -1) + '»';
    }
    return s;
  }).join(' ');
}

data.forEach((s) => replaceQuotes(s));
ready
Regex replacement
function replaceQuotes(str) {
    return str
        .replace(/\x27/g, '\x22')
        .replace(/(\w)\x22(\w)/g, '$1\x27$2')
        .replace(/(^)\x22(\s)/g, '$1»$2')
        .replace(/(^|\s|\()"/g, '$1«')
        .replace(/"(\;|\!|\?|\:|\.|\,|$|\)|\s)/g, '»$1');
}

data.forEach((s) => replaceQuotes(s));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.