JavaScriptで文字列がスペースで終わっているかどうかを検証したい。前もって感謝します。
var endSpace = / \s$/;
var str = "hello world ";
if (endSpace.test(str)) {
window.console.error("ends with space");
return false;
}
JavaScriptで文字列がスペースで終わっているかどうかを検証したい。前もって感謝します。
var endSpace = / \s$/;
var str = "hello world ";
if (endSpace.test(str)) {
window.console.error("ends with space");
return false;
}
\s
[space]
スペースを表すため、正規表現を追加する必要はありません
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>
var endSpace = / \s$/;
上記の行では、実際には 2 つのスペースを使用しています。1 つは ( ) で、2 つ目は
\s
です。それが理由です。コードが機能していません。それらの 1 つを削除します。
var endSpace = / $/;
var str="hello world ";
if(endSpace.test(str)) {
window.console.error("ends with space"); return false;
}
次のコード スニペットを使用できます -
if(/\s+$/.test(str)) {
window.console.error("ends with space");
return false;
}
$(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>