Search code examples
javascriptends-with

How to check for string.endsWith and ignore whitespace


I have this working function, to check if a string ends with a :

var string = "This is the text:"

function (string) {
  if (string.endsWith(':')) {
    // ends with :
  }
  if (string.endsWith(': ')) {
   // ends with : and a space
  }
  else {
    // does not end with :
  }
}

I also want to check if string ends with a colon followed by space, or even two spaces: :_ or :__ (where underscore represent spaces in this syntax).

Any ideas on how to implement this whithout using multiple if statements or defining every possible combination of colon and spaces? Let's assume there could be any number of spaces after the colon, but if last visible character is colon, I want to catch it in my function.


Solution

  • You can use String.prototype.trimEnd to remove whitespace from the end, and then check that:

    function (string) {
      if (string.endsWith(':')) {
        // ends with :
      }
      else if (string.trimEnd().endsWith(':')) {
       // ends with : and white space
      }
      else {
        // does not end with :
      }
    }