I'm trying to check if a string has white space. I found this function but it doesn't seem to be working:
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;
}
By the way, I added quotes to RegExp
.
Is there something wrong? Is there anything better that I can use? Hopefully JQuery.
This question is related to
javascript
whitespace
One simple approach you could take is to compare the length of the original string with that of the string to have whitespaces replaced with nothing. For example:
function hasWhiteSpaces(string) {
if (string.length == string.replace(" ", "").length) {return false}
return true
}
This function checks for other types of whitespace, not just space (tab, carriage return, etc.)
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
If you don't want to use Lodash, then here is a simple some
implementation with 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;
};
Then just replace some
with ssome
.
const hasWhitespace = char => some(
w => char.indexOf(w) > -1,
whitespaceCharacters
)
For those in Node, use:
const { some } = require('lodash/fp');
Here is my suggested validation:
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;
}
}
With additions to the language it is much easier, plus you can take advantage of early return:
// 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));
I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.
A few others have posted answers. There are some obvious problems, like it returns false
when the Regex passes, and the ^
and $
operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).
Besides that, the issue is just a typo.
Change this...
var reWhiteSpace = new RegExp("/^\s+$/");
To this...
var reWhiteSpace = new RegExp("\\s+");
When using a regex within RegExp()
, you must do the two following things...
/
brackets.\\s
in place of \s
, etc.Full working demo from source code....
$(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'));
});
_x000D_
<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>
_x000D_
Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/"
characters are sufficient.
/^\s+$/
is checking whether the string is ALL whitespace:
^
matches the start of the string.\s+
means at least 1, possibly more, spaces.$
matches the end of the string.Try replacing the regex with /\s/
(and no quotes)
Source: Stackoverflow.com