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?
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: / $/
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With