如何使用Javascript将Json与字符串匹配

时间:2015-07-10 09:10:52

标签: jquery regex json

我需要做什么:

  • 我需要将Json与string匹配。

案例1:在Json中设置行业数据时

        ["", "app.php", "automotive", "tradeshows"]

JQuery代码:

  $( document ).ready(function() 
 {


    var match =  window.location.pathname.split("/");
    console.log(match[3]);

    if(match[3]=="conferences")
    {
         console.log("true");
    $('#radio3').prop('checked', true);

    }
    else if(match[3]=="tradeshows")
    {
        console.log("afeef");
        $('#radio2').prop('checked', true);
    }
    else
    {
        $('#radio1').prop('checked', true);
    }



   });

案例2:未在Json中设置行业数据时

     ["", "app.php",  "tradeshows"]
  • 在这种情况下,匹配将失败。

  • 在JQuery中匹配Json和string有没有其他方法?

  • 我需要将Json与string匹配,那么还有其他方法可以让Json与string匹配吗?

1 个答案:

答案 0 :(得分:0)

您可以使用jQuery indexOf()来检测automotive是否可用。请参阅以下代码



function myFunction(page) {
    var pages = ["", "app.php", "automotive", "tradeshows"];
    var a = pages.indexOf(page);
    document.getElementById("demo").innerHTML = a;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click the button to display the position of the element "tradeshows":</p>

<button onclick="myFunction('automotive')">Check for automotive</button>
<button onclick="myFunction('automotive1')">Check for automotive1</button>

<p id="demo"></p>
&#13;
&#13;
&#13;

注意: indexOf方法是在JavaScript 1.6中引入的,在Internet Explorer 8及更早版本中不起作用。