Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the string ends with space in javascript?

I want to validate if the string ends with space in JavaScript. Thanks in advance.

var endSpace = / \s$/;
var str = "hello world ";

if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
}
like image 345
user3610534 Avatar asked Dec 10 '22 22:12

user3610534


2 Answers

You can use endsWith(). It will be faster than regex:

myStr.endsWith(' ')

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

If endsWith is not supported by browser, you can use the polyfill provided by MDN:

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.lastIndexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
}
like image 92
Tushar Avatar answered Dec 27 '22 10:12

Tushar


\s represent a space, there is no need to add [space] in the regex

var endSpace = /\s$/;
var str = "hello world ";

if (endSpace.test(str)) {
  window.console.error("ends with space");
  //return false; //commented since snippet is throwing an error
}

function test() {
  var endSpace = /\s$/;
  var str = document.getElementById('abc').value;

  if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
  }
}
<input id="abc" />
<button onclick="test()">test</button>
like image 45
Arun P Johny Avatar answered Dec 27 '22 10:12

Arun P Johny