Javascript – string ends with check

ECMAScript 6 String.prototype.endsWith() method can be used to check if a string ends with a suffix. But it is not yet supported by all browsers. Another approach is to use substring.

if (big.indexOf(small) == big.length-small.length) {
   ...
}

Example – case sensitive string ends with check

<script>
  var big = "Hello World";
  var small = "World";
  if (big.substring(big.length-small.length, big.length) == small) {
    document.write("big string ends with small string");
  }
</script>
refresh

Example – string ends with check ignoring case

<script>
  var big = "hello World";
  var small = "world";
  if (big.toLowerCase().substring(big.length-small.length, big.length) == small.toLowerCase()) {
    document.write("big string ends with small string (ignoring case)");
  }
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments