0

I'm horrible at RegEx and I need a regex to test if a certain string ends a certain way. For example, if the RegEx tests for ending with foo, "somestringfoo" -> True and "someotherFoostring" -> False. It needs to be case sensitive and work with alphanumeric and underscore. Here is what I've got, but I can't get it to work:

var test = RegExp.test('/foo$/');
nickb
  • 59,313
  • 13
  • 108
  • 143
Stephen Smith
  • 485
  • 1
  • 6
  • 14

3 Answers3

2

You would do it this way:

/foo$/.test("somestringfoo")
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • I tried using that, but I get invalid regex: if (/$/.test(xmlhttp.responseText)) { mySound.play(); } – Stephen Smith Jul 08 '12 at 15:39
  • This is an invalid regexp, yes. You of course need to escape the delimiters. – Bergi Jul 08 '12 at 15:43
  • @Stephen If you don’t need the features of regular expression but only a plain string matching, you should use simple string operations instead: `str.substr(-pattern.length) === pattern`. – Gumbo Jul 08 '12 at 15:43
1

this should do the work:

function isFoo(string){
  var pattern = /foo$/;  
  return pattern.test(string);
}
Yaron U.
  • 7,681
  • 3
  • 31
  • 45
1

test is a method of the regexp object, so it would be /foo$/.test(someString) or new Regexp("foo$").test(someString).

However, testing a string for ending with a certain substring does not need regular expressions, see endsWith in JavaScript.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375