0
\$\begingroup\$

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

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.