从ajax获取特定的行

时间:2011-01-02 16:39:28

标签: javascript jquery ajax

我有这段代码:

<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script>
    var TheSource;
    $.ajax({
        url: "http://www.domain.com/",
        cache: false,
        success: function(html){
            TheSource = html;
            TheSource = TheSource.substring(1,TheSource.indexOf("</head>"));
            TheTitle = TheSource.substring(TheSource.indexOf("<title>")+7,TheSource.indexOf("</title>"));
            alert(TheSource);
        }
    });
</script>
</head>
<body>
</body>
</html>

我从我的网站获得了我需要的源代码部分,我想从TheSource获取以var开头的行(我有几个)

我的问题是:

  1. 如何将此返回的html拆分为行?
  2. 我如何获得每行并检查它的开头?
  3. 如何删除脚本缩进? (因为我有几行以缩进开头的var

1 个答案:

答案 0 :(得分:2)

这是一种方法:

var TheSource = "var abcd; abcd; abcdabcd; var abcde ; var abcdef;    \tvar abcd;\tvar;var;no var; \t no var;\nanother line;\nvar new line;";


var lines = TheSource.split(/;/); // get each line
var foundLines = new Array(); 
for (index in lines) {
    var line = lines[index];
    if (line.search(/^\s*var/)!=-1) { // look for "var" at the beginning of the string (ignoring whitespaces)
        foundLines.push(line + ";"); //add a semicolon back
    }
}

document.write(foundLines.join("<br>"));
相关问题