![](/img/trans.png)
[英]Check if a string in an array has white space character in javascript/jquery
[英]Check if a string has white space
我正在嘗試檢查字符串是否有空格。 我找到了這個 function 但它似乎不起作用:
function hasWhiteSpace(s)
{
var reWhiteSpace = new RegExp("/^\s+$/");
// Check for white space
if (reWhiteSpace.test(s)) {
//alert("Please Check Your Fields For Spaces");
return false;
}
return true;
}
順便說一句,我在RegExp
中添加了引號。
有什么不對? 有什么更好的我可以使用嗎? 希望JQuery。
您可以簡單地對輸入字符串使用indexOf方法:
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
或者您可以在簡單的 RegEx 上使用測試方法:
function hasWhiteSpace(s) {
return /\s/g.test(s);
}
這還將檢查其他空白字符,如 Tab。
你的正則表達式不會匹配任何東西,因為它是。 您肯定需要刪除引號—— "/"
字符就足夠了。
/^\\s+$/
正在檢查字符串是否是所有空白:
^
匹配字符串的開頭。\\s+
表示至少 1 個,可能更多,空格。$
匹配字符串的結尾。 嘗試用/\\s/
替換正則表達式(並且沒有引號)
此函數檢查其他類型的空格,而不僅僅是空格(制表符、回車符等)
import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', ' ',
'\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
'\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true
如果你不希望使用Lodash ,那么這里是一個簡單的some
與2個實現s
:
const ssome = (predicate, list) =>
{
const len = list.length;
for(const i = 0; i<len; i++)
{
if(predicate(list[i]) === true) {
return true;
}
}
return false;
};
然后只需將some
替換為ssome
。
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
對於 Node 中的用戶,請使用:
const { some } = require('lodash/fp');
其他一些人發布了答案。 有一些明顯的問題,比如它在 Regex 通過時返回false
,並且^
和$
運算符指示開始/結束,而問題正在尋找(任何)空格,而不是:只包含空格(正則表達式正在檢查) )。
除此之外,這個問題只是一個錯字。
改變這...
var reWhiteSpace = new RegExp("/^\s+$/");
對此...
var reWhiteSpace = new RegExp("\\s+");
在RegExp()
使用正則RegExp()
,您必須執行以下兩件事...
/
括號。\\\\s
代替\\s
等。來自源代碼的完整工作演示......
$(document).ready(function(e) { function hasWhiteSpace(s) { var reWhiteSpace = new RegExp("\\\\s+"); // Check for white space if (reWhiteSpace.test(s)) { //alert("Please Check Your Fields For Spaces"); return 'true'; } return 'false'; } $('#whitespace1').html(hasWhiteSpace(' ')); $('#whitespace2').html(hasWhiteSpace('123')); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> " ": <span id="whitespace1"></span><br> "123": <span id="whitespace2"></span>
通過添加語言,它變得更加容易,而且您可以利用早期回報:
// Use includes method on string
function hasWhiteSpace(s) {
const whitespaceChars = [' ', '\t', '\n'];
return whitespaceChars.some(char => s.includes(char));
}
// Use character comparison
function hasWhiteSpace(s) {
const whitespaceChars = [' ', '\t', '\n'];
return Array.from(s).some(char => whitespaceChars.includes(char));
}
const withSpace = "Hello World!";
const noSpace = "HelloWorld!";
console.log(hasWhiteSpace(withSpace));
console.log(hasWhiteSpace(noSpace));
console.log(hasWhiteSpace2(withSpace));
console.log(hasWhiteSpace2(noSpace));
我沒有運行性能基准測試,但這些應該比正則表達式快,但是對於小文本片段,無論如何不會有太大區別。
我認為我們可以使用includes()
message :string = "Hello world";
message2 : string = "Helloworld";
message.includes(' '); // true
message2.inlcudes(' ')// false
const checkEmpty = (title: string) => {
let testString = title.replaceAll(" ", "");
if (testString.length === 0) {
return true;
}
return false;
};
這就是我用來檢查輸入是否僅包含空格的內容您也可以只使用“.includes”運算符來檢查字符串中是否包含空格:)
這是我建議的驗證:
var isValid = false;
// Check whether this entered value is numeric.
function checkNumeric() {
var numericVal = document.getElementById("txt_numeric").value;
if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
alert("Please, enter a numeric value!");
isValid = false;
} else {
isValid = true;
}
}
您可以采取的一種簡單方法是將原始字符串的長度與字符串的長度進行比較,以將空格替換為空。 例如:
function hasWhiteSpaces(string) {
if (string.length == string.replace(" ", "").length) {return false}
return true
}
function hasWhiteSpace(s) {
return s.includes(' ')
}
如果您使用 ECMAScript6 (ES6) 或更新版本,最簡單的方法如下所示
// looking just for spaces
function hasWhiteSpace(s) {
return s.includes(' ');
}
上述功能有幾個限制,
如果我們需要使用正則表達式來匹配所有可能的空白字符,我們可以使用自 ECMAScript1 (ES1) 以來可用的search
選項:
// looking for spaces, tabs, line breakers, etc.
// live example: https://www.w3schools.com/jsref/jsref_regexp_whitespace.asp
function hasWhiteSpace(s) {
return s.search(/\s/);
}
// looking just for spaces, equivalent to includes option
function hasWhiteSpace(s) {
return s.search(/ /);
}
這還將檢查其他空白字符,例如 Tab。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.