JavaScriptで空/未定義/ヌル文字列をチェックする方法は?
-
03-07-2019 - |
質問
このスレッドを見ましたが、 JavaScript固有の例は見られませんでした。 JavaScriptで使用できる単純な string.Empty
がありますか、それとも""
をチェックするだけの場合ですか?
解決
値があるかどうかだけを確認したい場合は、次を実行できます
if (strValue) {
//do something
}
nullを超える空の文字列を具体的に確認する必要がある場合、 ===
演算子(実際、比較対象の文字列であることがわかります)。
if (strValue === "") {
//...
}
他のヒント
文字列が空か、nullか、未定義かを確認するには、次を使用します。
function isEmpty(str) {
return (!str || 0 === str.length);
}
文字列が空白か、nullか、未定義かを確認するには、次を使用します。
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
文字列が空白であるか、空白のみを含むかどうかを確認するには:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
上記はすべて良好ですが、これはさらに改善されます。 !!
( not )演算子を使用します。
if(!!str){
some code here;
}
または型キャストを使用:
if(Boolean(str)){
codes here;
}
同じ機能を実行し、変数をbooleanにキャストします。 str
は変数です。
null、undefined、0,000、""、false
に対して false
を返します。
文字列" 0"に対して true
を返します。および空白" "。
文字列が単なる空のスペースではないことを確認する必要がある場合(これはフォームの検証のためだと思います)、スペースを置換する必要があります。
if(str.replace(/\s/g,"") == ""){
}
str.Empty
に到達できる最も近いもの(strがStringであるという前提条件)は次のとおりです。
if (!str.length) { ...
使用:
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
試してください:
if (str && str.trim().length) {
//...
}
機能:
function is_empty(x)
{
return (
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
p.s。 Javascriptでは、
の後にLine-Breakを使用しないでください。return
;
var s; // undefined
var s = ""; // ""
s.length // 0
JavaScriptには空の文字列を表すものは何もありません。 length
(varが常に文字列であることがわかっている場合)または""
lodash を使用できます。 _.isEmpty(値)。
{}
、 ''
、 null
、 undefined
などの多くのケースをカバーしています。
ただし、 true
を返します/ Data_structures "rel =" noreferrer "> _。isEmpty(10)
や _。isEmpty(Number.MAX_VALUE)
などのJavascriptプリミティブデータ型は両方とも< code> true 。
最も効率的な方法についてはあまり心配しません。あなたの意図に最も明確なものを使用してください。私にとっては、通常は strVar ==&quot;&quot;
です。
編集: Constantin からのコメントごとに、strVarが整数値0を含むことができた場合、それは実際、意図を明確にする状況の1つになります。
正規表現を使用することもできます:
if((/^\s*$/).test(str)) { }
空の文字列または空白文字で埋められている文字列をチェックします。
多くの答え、そしてさまざまな可能性!
迅速かつ簡単な実装に疑いの余地はありません。 if(!str.length){...}
ただし、他にも多くの例があります。これを行うのに最適な機能的な方法は、次のとおりです。
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;
}
}
少し過剰です、私は知っています。
-
var a;
が存在することを確認 -
値の
をテストしますfalseスペース
を削除し、emptiness
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
また、空白で満たされた文字列を「空」とみなす場合。 この正規表現でテストできます:
!/\S/.test(string); // Returns true if blank.
通常、このようなものを使用します
if (!str.length) {
//do some thing
}
文字列内のヌル文字の可能性を考慮に入れた答えに気付いていません。たとえば、ヌル文字列がある場合:
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
そのヌル性をテストするには、次のようなことができます:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
ヌル文字列と空の文字列で機能し、すべての文字列にアクセスできます。さらに、他のJavaScriptの空文字または空白文字(つまり、改行しないスペース、バイトオーダーマーク、行/段落区切りなど)を含むように展開できます。
空の文字列だけでなく空白の文字列も検出する必要がある場合、Goralの答えに追加します。
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
これらの答えはすべて素晴らしいです。
しかし、変数が文字列であること、スペースのみが含まれていること(これは私にとって重要です)、「0」(文字列)が含まれていることを確認できません。
私のバージョン:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
jsfiddle のサンプル。
通常、次のようなものを使用します。
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
組み合わせを使用します。最速のチェックが最初です。
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);
}
空白文字列を無視すると、これを使用してnull、空、未定義を確認できます:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
簡潔で未定義のプロパティに対して機能しますが、最も読みやすいものではありません。
テスター関数に文字列ではなく空でも空でもない値を渡すとどうなるかを調査しました。多くの人が知っているように、(0 ==&quot;&quot;)はjavascriptではtrueですが、0は値であり、空またはnullではないため、テストすることをお勧めします。
次の2つの関数は、未定義、null、空/空白の値に対してのみtrueを返し、数値、ブール値、オブジェクト、式など、その他すべてに対してfalseを返します。
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
さらに複雑な例もありますが、これらは単純で一貫した結果をもたらします。 (値== null)チェックに含まれているため、未定義をテストする必要はありません。次のように文字列に追加することにより、C#の動作を模倣することもできます。
String.IsNullOrEmpty = function (value) { ... }
Stringクラスのインスタンスがnullの場合、エラーになるため、Stringsプロトタイプに入れたくない:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
次の値配列でテストしました。疑わしい場合は、ループして機能をテストできます。
// 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; } }]
];
空の文字列であるかどうかを確認するには:
if(val==="")...
空の文字列か、値なし(null、undefined、0、NaN、false、...)と論理的に同等かどうかを確認するには:
if(!val)...
一方、 null、undefined、 ''、 ''、{}、[] など、すべての「空」をチェックする1つの関数を使用できます。 だから私はこれを書いた。
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;
}
}
ユースケースと結果。
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
isEmpty()
メソッドはありません。タイプと長さを確認する必要があります:
if (typeof test === 'string' && test.length === 0){
...
test
が undefined
または null
の場合の実行時エラーを回避するには、型チェックが必要です。
チェックする変数が文字列であると想定しないでください。この変数の長さが文字列であると想定しないでください。
重要なのは、アプリが何をする必要があり、受け入れることができるかについて慎重に考えることです。堅牢なものを構築します。
メソッド/関数が空でない文字列のみを処理する必要がある場合、引数が空でない文字列であるかどうかをテストし、「トリック」を実行しないでください。
慎重にではなく、ここでいくつかのアドバイスに従えば爆発する何かの例として。
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'
だから、私は固執します
if (myVar === '')
...
これを試してください
str.value.length == 0
JavaScript のネイティブ String オブジェクトに簡単に追加し、何度も何度も再利用できます...
''
空の文字列をチェックしたい場合、以下のコードのような単純なものがあなたのために仕事をすることができます:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
それ以外の場合は、空の文字列 ''
と ''
の両方をチェックしたい場合は、 trim()
、以下のコードのようなもの:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
この方法で呼び出すことができます:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return 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' />
これは、フィールドが空かどうかを確認する一般的な方法でもあります。