如何在 javascript 中提取子字符串

How can I extract a substring in javascript

我需要从这个字符串中提取一个子字符串,特别是 "Sweet Heart" Package (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">'); 但它不是 return 一个有效的整数位置,它实际上没有 return 任何东西......我想知道我做错了什么以及我最好如何解决这个问题.

谢谢!

您不能跨多行声明一个 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 ); ?>;