Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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]));  
}

share|improve this question
up vote 3 down vote accepted

It's weird that if either string is undefined, then the function returns neither true nor false, but undefined.

What you wrote is not a string equality checker; it's a regular expression matcher. If secondString contains any special regular expression characters (like a $), then the test falls apart.

You could fix that problem by escaping the regex. But that seems silly, when you could just use firstString === secondString to check for equality.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.