Skip to main content
2 of 2
added 1 character in body; edited tags; edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

JavaScript function to compare strings

I've written this function for to check if two strings are equal.

Can I improve it?

Is there a better way to accomplish the task?

// Compares two Strings concerning equality.

// -- Parameter --------------------------------
// 1. String - The string to compare against.
// 2. String - The string to compare with.

// -- Return -----------------------------------
// Boolean - True if both string are equal.

function compareSrings(firstString, secondString) {
  if ( firstString === undefined || 
       secondString === undefined ) return;
  
  var needle = new RegExp('^' + secondString + '$');
  
  return (firstString.length === secondString.length) && 
         (firstString.search(needle) === 0);
}
// --- TEST -----------------------------------------

var first = [ 'Test',
              'Demo',
              '123',
              'Alpha',
              'Beta',
              'Gamma',
              'Delta Epsilon',
              'Rot Gelb Grün Blau',
              'javaScript',
              '$Demo123',
              '',
              'xyz'
            ];
var second = [ 'Test',
              'Demo',
              '1234',
              'Alpha',
              'beta',
              'Gamma',
              'Delta psilon',
              'Rot Gelb Grün Blau',
              '',
              'somethingElse',
              ''
            ];
 
for (var i = 0; i < first.length; i++) {
  console.log( '%s === %s => %s', 
               first[i],
               second[i],
               compareSrings(first[i], second[i]));  
}

bo256
  • 129
  • 6