detect differences between two strings with Javascript

前端 未结 2 1350
情深已故
情深已故 2020-11-29 08:12

With Javascript, I want to check how many differences there are between two strings.

Something like:

var oldName = \"Alec\";
var newName = \"Alexand         


        
相关标签:
2条回答
  • 2020-11-29 09:08

    I don't have a Javascript implementation on hand per se, but you're doing something for which well-established algorithms exist. Specifically, I believe you're looking for the "Levenshtein distance" between two strings -- i.e. the number of insertions, substitutions and deletions (assuming you are treating a deletion as a change).

    The wikipedia page for Levenshtein distance has various pseudo-code implementations from which you could start, and references which may also help you.

    0 讨论(0)
  • 2020-11-29 09:15

    Alternative implemenation:

    /**
     * Computes the Levenshtein edit distance between two strings.
     * @param {string} a
     * @param {string} b
     * @return {number} The edit distance between the two strings.
     */
    goog.string.editDistance = function(a, b) {
      var v0 = [];
      var v1 = [];
    
      if (a == b) {
        return 0;
      }
    
      if (!a.length || !b.length) {
        return Math.max(a.length, b.length);
      }
    
      for (var i = 0; i < b.length + 1; i++) {
        v0[i] = i;
      }
    
      for (var i = 0; i < a.length; i++) {
        v1[0] = i + 1;
    
        for (var j = 0; j < b.length; j++) {
          var cost = Number(a[i] != b[j]);
          // Cost for the substring is the minimum of adding one character, removing
          // one character, or a swap.
          v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);
        }
    
        for (var j = 0; j < v0.length; j++) {
          v0[j] = v1[j];
        }
      }
    
      return v1[b.length];
    };
    
    0 讨论(0)
提交回复
热议问题