Efficiently replace all accented characters in a string?

后端 未结 21 2964
别跟我提以往
别跟我提以往 2020-11-22 04:35

For a poor man\'s implementation of near-collation-correct sorting on the client side I need a JavaScript function that does efficient single character rep

21条回答
  •  清歌不尽
    2020-11-22 05:16

    I just wanted to post my solution using String#localeCompare

    const base_chars = [
      '1', '2', '3', '4', '5', '6', '7', '8', '9',
      '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
      'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
      'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
      '-', '_', ' '
    ];
    const fix = str => str.normalize('NFKD').split('')
        .map(c => base_chars.find(bc => bc.localeCompare(c, 'en', { sensitivity: 'base' })==0))
        .join('');
    
    const str = 'OÒ óëå-123';
    console.log(`fix(${str}) = ${fix(str)}`);

提交回复
热议问题