-1

I'm trying to write a regexp which should return true if a given string foo ends with the given string bar. E.g:

function solution(str, ending)
{
  var pattern = "/" + ending + "$/";
  var regex = new RegExp(pattern, "i");
  console.log( str + ", " + ending + " , " + regex.source);
  return regex.test(str);
}

However, if I test this using the following input:

console.log( solution("samurai", "ai") );

I get the following console output:

samurai, ai , /ai$/
false 

The pattern seems correct to me, so why is it returning false for 'samurai' ending with 'ai' ?

Ali
  • 261,656
  • 265
  • 575
  • 769
  • I think you should read more about regexes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions , as well as understanding the use of an "escape" function, in case the `pattern` may include regex characters: http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript – Ian Oct 11 '13 at 02:38

2 Answers2

2

If you invoke the RegExp constructor, you don't need to put / characters around your pattern. That's only for when you're using a regular expression literal.

Try this:

function solution(str, ending)
{
  var pattern = ending + "$";
  var regex = new RegExp(pattern, "i");
  console.log( str + ", " + ending + " , " + regex.source);
  return regex.test(str);
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

new RegExp("/foo/") is /\/foo\//. The slashes are only needed when you're constructing a regex literal.

Take out the slashes from your string and it'll work.

You can also do this without regex:

str.lastIndexOf(ending) === str.length - ending.length;
Blender
  • 289,723
  • 53
  • 439
  • 496