如何在javascript中提取子字符串

时间:2015-01-25 06:09:03

标签: javascript find substring indexof

我需要提取一个子字符串,特别是" Sweet Heart"来自此字符串的包(SPA02)

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Find String</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = '<div class="view view-commerce-line-item-table view-id-commerce_line_item_table view-display-id-default view-dom-id-57765ff55f834d6a7ec1b8f510768a90">
<div class="view-content">
<table class="views-table cols-4"><thead><tr><th class="views-field views-field-line-item-title">
            Title          </th>
<th class="views-field views-field-commerce-unit-price">
            Unit price          </th>
<th class="views-field views-field-quantity">
            Quantity          </th>
<th class="views-field views-field-commerce-total views-align-right">
            Total          </th>
</tr></thead><tbody><tr class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">
             "Sweet Heart" Package    (SPA02)          </td>
<td class="views-field views-field-commerce-unit-price">
            135.00  CAD          </td>
<td class="views-field views-field-quantity">
            1          </td>
<td class="views-field views-field-commerce-total views-align-right">
            135.00  CAD          </td>
</tr></tbody></table></div>
</div>';
    var n = str.indexOf('class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">');
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

我试过这个来找到字符串的开头: str.indexOf('class="odd views-row-first views-row-last"><td class="views-field views-field-line-item-title">'); 但它并没有返回一个有效的整数位置,它实际上并没有返回任何东西......而且我想知道我做错了什么以及我最好怎么做关于这个。

谢谢!

1 个答案:

答案 0 :(得分:1)

您不能跨多行声明JavaScript字符串。您将收到语法错误。

  

SyntaxError:unterminated string literal

替代选项包括:

转义换行符:

var str = '<div>\
    test\
</div>';

级联:

var str = '<div>' + 
'    test' + 
'</div>';

将其存储在DOM元素中:

<script id="my_str" type="text/html">
<div>
    test
</div>
</script>

并像这样检索:

doucment.getElementById('my_str').innerHTML;

使用PHP:

var str = <?php echo json_encode( $your_html_string ); ?>;