Como é que se verifica se existe um texto vazio no JavaScript?
30 answers
Se você só quer verificar se há algum valor, você pode fazer
if (strValue) {
//do something
}
Se você precisar verificar especificamente para uma cadeia vazia sobre nula, eu pensaria que verificar contra ""
é a sua melhor aposta, usando o operador ===
(de modo que você saiba que é, de facto, uma cadeia que está a comparar).
if (strValue === "") {
//...
}
Para verificar se um texto está vazio, nulo ou indefinido, eu uso:
function isEmpty(str) {
return (!str || 0 === str.length);
}
Para verificar se um texto está em branco, nulo ou indefinido eu uso:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
Para verificar se um texto está em branco ou contém apenas espaço em branco:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
!!
(não operador.
if(!!str){
some code here;
}
Ou utilizar o tipo de fundição:
if(Boolean(str)){
codes here;
}
Ambos fazem a mesma função, tipo molda a variável para booleana, onde str
é uma variável.
Devolve false
para null,undefined,0,000,"",false
.
Devolve true
o texto " 0 "e o espaço em branco" ".
Se tiver de se certificar de que o texto não é apenas um monte de espaços vazios (presumo que isto seja para validação do formulário), terá de fazer uma substituição nos espaços.
if(str.replace(/\s/g,"") == ""){
}
A coisa mais próxima que você pode chegar a str.Empty
(com a condição prévia de que o str é uma String) é:
if (!str.length) { ...
Eu uso:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case typeof this == "undefined":
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
var s; // undefined
var s = ""; // ""
s.length // 0
Não há nada que represente um texto vazio no JavaScript. Faça uma verificação contra length
(Se souber que a var será sempre uma string) ou contra ""
Tenta:
if (str && str.trim().length) {
//...
}
Não me preocuparia muito com o método mais eficiente . Use o que é mais claro para a sua intenção. Para mim isso é normalmente strVar == ""
.
Editar: por Comentário de Constantin , se o strVar pudesse saber como acabar por conter um valor inteiro 0, então isso seria de facto uma daquelas situações de esclarecimento de intenções.
Função:
function Is_Empty_or_Undefined (MyVar)
{
return
(
(typeof MyVar== 'undefined')
||
(MyVar == null)
||
(MyVar == false) //same as: !MyVariable
||
(MyVar.length == 0)
||
(MyVar == "")
||
(MyVar.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(MyVar))
||
(/^\s*$/.test(MyVar))
);
}
Pode utilizar lodash : _.isEmpty (valor).
Cobre muitos casos como {}
, ''
, null
, undefined
etc.
Mas devolve sempre true
para Number
tipo de Javascript tipos de dados primitivos como _.isEmpty(10)
ou {[7] } ambos devolve true
.
Você também pode escolher regexps:
if((/^\s*$/).test(str)) { }
Verifica se há cadeias de caracteres que estejam vazias ou cheias de espaços em branco.
- Verifique se
var a;
Existe -
Aparar o
false spaces
no valor, e depois testar paraemptiness
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
Sem dúvida para uma implementação rápida e simples o vencedor é: if (!str.length) {...}
No entanto, como muitos outros exemplos estão disponíveis. O melhor método funcional para fazer isso, eu sugeriria:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
{
return true;
}
else
{
return false;
}
}
Também, no caso de considerar um texto preenchido em branco como "vazio". Pode testá-lo com esta expressão:
!/\S/.test(string); // Returns true if blank.
if (!str.length) {
//do some thing
}
Eu não notei uma resposta que leva em conta a possibilidade de caracteres nulos em uma string. Por exemplo, se tivermos uma cadeia de caracteres nula:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
Para testar a sua nulidade, pode - se fazer algo assim:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
Ele funciona em uma string nula, e em uma string vazia e é acessível para todas as strings. Além disso, ele poderia ser expandido para conter outros caracteres JavaScript vazios ou em branco (ou seja, espaço não quebrável, marca de ordem de byte, linha/parágrafo separador, etc.).
Se for necessário detectar não só cadeias vazias, mas também cadeias em branco, vou adicionar à resposta do Goral:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
Se eu usar uma combinação, os controlos mais rápidos são os primeiros.
function isBlank(pString){
if (!pString || pString.length == 0) {
return true;
}
// checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
Ignorando os textos em branco, poderá usar isto para verificar se é nulo, vazio e indefinido:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
Conciso e funciona para propriedades indefinidas, embora não seja o mais legível.
Mas não posso ter a certeza que a variável é uma string, não contém apenas espaços (isto é importante para mim), e pode conter '0' (string).
A minha versão:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Amostra em jsfiddle .
Costumo usar algo do género:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
Fiz algumas pesquisas sobre o que acontece se passar um valor não-string e não-vazio/nulo para uma função de teste. Como muitos sabem, (0 ="") é verdadeiro em javascript, mas como 0 é um valor e não vazio ou nulo, você pode querer testar para ele.
As seguintes duas funções retornam verdadeiras apenas para valores indefinidos, nulos, vazios/em branco e falsos para tudo o resto, tais como números, booleanos, objectos, expressões, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
Existem exemplos mais complicados, mas estes são simples. e dar resultados consistentes. Não há necessidade de testar para indefinido, uma vez que está incluído em (value = null) check. Você também pode imitar o comportamento de C# adicionando - os ao texto assim:
String.IsNullOrEmpty = function (value) { ... }
Você não quer colocá-lo em Strings protótipo, porque se a instância da String-class é nula, ele vai errar:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
Testei com o seguinte conjunto de valores. Você pode loop através dele para testar suas funções se em dúvida.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // valid number in some locales, not in js
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
Para verificar se é exactamente um texto vazio:
if(val==="")...
Para verificar se é uma cadeia vazia ou um equivalente lógico para nenhum valor (null, indefinido, 0, NaN, false, ...):
if(!val)...
Não há nenhum método isEmpty()
, você tem que verificar para o tipo e o comprimento:
if (typeof test === 'string' && test.length === 0){
...
A verificação do tipo é necessária para evitar erros de tempo de execução quando test
é undefined
ou null
.
Tenta isto
str.value.length == 0
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Usar casos e resultados.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
Esta é também uma forma genérica de verificar se o campo está vazio.
Não assumas que a variável que verificas é uma string. Não suponha que se este var tem um comprimento, então é um fio.
A coisa é: Pense cuidadosamente sobre o que o seu aplicativo deve fazer e pode aceitar. Construir algo robusto.
Se o seu método / função só deve processar uma cadeia de caracteres não vazia, então teste se o argumento é uma cadeia não vazia e não faça algum 'truque'.
Como um exemplo de algo que explodirá se você seguir alguns conselhos aqui não cuidadosamente.
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
Então, eu ficaria com
if (myVar === '')
...
Você deve sempre verificar para o tipo também, uma vez que JavaScript é um idioma datilografado pato, então você pode não saber quando e como os dados mudaram no meio do processo. Então, aqui está a melhor solução:
var str = "";
if (str === "") {
//...
}