Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if last character in a string is 'space'?

I have a code as follows in this fiddle:

<span id="someid">check this phrase </span><br>
<span id="result"></span> 

Here I have placed a space after the word 'phrase', but when I put a conditional statement it always returns one result. How is it possible to check the end of the string for a space?

like image 985
Javier Brooklyn Avatar asked Feb 13 '13 17:02

Javier Brooklyn


1 Answers

You can check whether the text value ends with space by the following regular-expression:

/\s$/

/\s$/ means one space at the end of the string.

JSFiddle

JavaScript

var mystring = $("#someid").text();

$("#someid").click( function (event) {
    if(/\s+$/.test(mystring)) {
        $("#result").text("space");    
    } else {
        $("#result").text("no space");

    }    
}); 

As jfriend00 noticed \s does not means only space, it's white-space [i.e. includes tab too (\t)]

If you need only space use: / $/.

like image 81
Minko Gechev Avatar answered Sep 22 '22 06:09

Minko Gechev