5

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;
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
user3610534
  • 61
  • 1
  • 1
  • 2

7 Answers7

6

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;
    };
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • What if I am checking to see if it ends with a space and 1 character? For example: `John R` matches but `John Ron` doesn't match. – Si8 Apr 11 '18 at 15:51
  • @Si8 Use regex. `/\s.$/`. To allow only alphabet at the end `/\s[a-z]$/i`. – Tushar Apr 12 '18 at 01:05
5

\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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2
var endSpace = / \s$/;

In the above line you are actually using 2 spaces, one is () and the second one is \s. That is the reason, your code is not working. Remove one of them.

var endSpace = / $/; 
var str="hello world "; 
if(endSpace.test(str)) { 
 window.console.error("ends with space"); return false; 
}
Zee
  • 8,420
  • 5
  • 36
  • 58
1

You may use the following code snippet -

if(/\s+$/.test(str)) {
   window.console.error("ends with space");
   return false;
}
Razib
  • 10,965
  • 11
  • 53
  • 80
1

You can try this also:

var str="hello world ";
var a=str.slice(-1);
if(a==" ") {
        console.log("ends with space");

}
Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28
0

$(document).ready(function() {
  $("#butCheck").click(function() {
    var checkString = $("#phrase").val();
    if (checkString.endsWith(' ')) {
      $("#result").text("space");
    } else {
      $("#result").text("no space");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="phrase"></input>
<input type="button" value="Check This" id="butCheck"></input>
<div id="result"></div>
Kurenai Kunai
  • 1,842
  • 2
  • 12
  • 22
0

Try this it will help to start and end white space in the string.

let begin_space_exp = /^\s/;
let end_space_exp = /\s$/;
/* Check for white space */
if (begin_space_exp.test(value) || end_space_exp.test(value)) {
  return false;
}`

I found /^\s+$/ has "AND" conditon like this begin_space_exp.test(value) && end_space_exp.test(value) then both should be true.

else you can use

(/^\s+|\s+$/g).test(value);