Replace nth occurrence of string

前端 未结 3 1238
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 01:16

For example:

\'abcjkjokabckjk\'.replace(\'/(abc)/g\',...)

If I want to replace a specify position \'abc\', what I can do?

Like this

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 01:54

    This can be done without RegEx.

    String methods String#indexOf, String#lastIndexOf can be used with String#substring

    var string = 'abcde|abcde|abcde|abcde',
      needle = 'abc',
      firstIndex = string.indexOf(needle),
      lastIndex = string.lastIndexOf(needle);
    
    // ----------------------------------------------------------------
    // Remove first occurence
    var first = string.substring(0, firstIndex) + '***' + string.substring(firstIndex + needle.length);
    document.getElementById('first').innerHTML = first;
    
    // ----------------------------------------------------------------
    // Remove last occurence
    var last = string.substring(0, lastIndex) + '***' + string.substring(lastIndex + needle.length);
    document.getElementById('last').innerHTML = last;
    
    // ----------------------------------------------------------------
    // Remove nth occurence
    // For Demo: Remove 2nd occurence
    var counter = 2, // zero-based index
      nThIndex = 0;
    
    if (counter > 0) {
      while (counter--) {
        // Get the index of the next occurence
        nThIndex = string.indexOf(needle, nThIndex + needle.length);
      }
      
      // Here `nThIndex` will be the index of the nth occurence
    }
    
    var second = string.substring(0, nThIndex) + '***' + string.substring(nThIndex + needle.length);
    document.getElementById('second').innerHTML = second;
    table tr td:nth-child(2) {
      color: green;
    }
    td {
      padding: 15px;
    }
    After replacing first occurence:
    After replacing last occurence:
    After replacing 2ndzero-based index occurence:

提交回复
热议问题