0

Java スクリプト関数で if 条件を使用していますが、Java スクリプトで && が使用されていることを確認しましたが、どういうわけか機能していません。誰でも提案できますか、ここで何が間違っている可能性がありますか:

if(slugs[i].match("^{{") && slugs[i].match("}}$"))
{
    alert(slugs[i] + "YES!");
}

チェックが正常に機能している場合はネストされています。

if(slugs[i].match("^{{"))
{
    if(slugs[i].match("}}$"))
    {
        alert(slugs[i] + "YES!");
    }
}
4

6 に答える 6

2

要するに:次のようなチェックを使用する必要がありますslugs[i].match(/^\{\{.*\}\}$/)

一方、このデモは、すべてが期待どおりに機能することを示しています。問題は別の場所にある可能性があります

var slugs = ['{{slug}}'];
var i = 0;
// your example #1
if(slugs[i].match("^\{\{") && slugs[i].match("\}\}$"))
{
    alert(slugs[i] + "YES!");
}
// your example #2
if(slugs[i].match("^\{\{"))
{
    if(slugs[i].match("\}\}$"))
    {
        alert(slugs[i] + "YES!");
    }
}

// corrected to use a single regex to accomplish the same thing
if(slugs[i].match(/^\{\{.*\}\}$/))
{
    alert(slugs[i] + "YES!");
}
于 2013-07-05T07:31:57.677 に答える
1

matchnullパターンが見つからない場合は返されます。これを試してください:

if (slugs[i].match("^{{") !== null && slugs[i].match("}}$") !== null)
{
    alert(slugs[i] + "YES!");
}
于 2013-07-05T07:34:29.440 に答える
1

There is no difference between the nested ifs and short-circuiting &&, your mistake must be elsewhere.

Anyway, I'd suggest using regex literals instead of the strings which are converted to regexes each time, and to call the boolean test method instead of making matches:

if (/^\{\{/.test(slugs[i]) && /\}\}$/.test(slugs[i]))
    alert(slugs[i]+" YES!");
于 2013-07-05T07:48:11.047 に答える
1

場合によっては引用符が機能しますが、正規表現を適切に作成していません。

match() MDN

これを試して

if(slugs[i].match(/^{{/) && slugs[i].match(/}}$/))
{
    alert(slugs[i] + "YES!");
}
于 2013-07-05T07:32:10.553 に答える
1

目的が単に一致するかどうかを判断することである場合は、.test()ではなくを使用することをお勧めします.match().matchは配列、またはnull.test()返しますが、ブール値を返します。これには別の構文が必要です。

これを試して:

if (/^{{/.test(slugs[i]) && /}}$/.test(slugs[i])) {
{
  alert(slugs[i] + "YES!");
}
于 2013-07-05T07:37:19.107 に答える
0

2つの条件をマージできます..

if(x = slugs[i].match(/^{{(.+)}}$/)){
  alert(x[1]+"YES!");
}
于 2013-07-05T07:41:05.727 に答える