Javascript – string starts with check

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

if (big.substring(0, small.length) == small) {
   ...
}

Example – case sensitive string starts with check

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

Example – string starts with check ignoring case

<script>
  var big = "hello world";
  var small = "Hello";
  if (big.toLowerCase().substring(0, small.length) == small.toLowerCase()) {
    document.write("big string starts 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