【问题标题】:How can I extract a substring in javascript如何在javascript中提取子字符串
【发布时间】:2015-01-25 06:09:03
【问题描述】:

我需要从这个字符串中提取一个子字符串,特别是 "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"&gt;&lt;td class="views-field views-field-line-item-title"&gt;'); 但它没有返回一个有效的整数位置,它实际上没有返回任何东西......我想知道我做错了什么以及我最好如何解决这个问题。

谢谢!

【问题讨论】:

  • 检查你的开发者控制台。看起来您有语法错误。具体来说,一个跨多行的字符串。
  • @AlexanderO'Mara 我绝对愿意,您是说跨多行的字符串在 javascript 中无效吗? :o
  • 是的,出于某种原因,这是设计决定。
  • @AlexanderO'Mara 那么我有什么替代品吗?
  • 如果它来自像 PHP 这样的服务器端脚本语言,请使用 JSON 编码器对其进行编码。如果没有,check out this questionthis question

标签: javascript find substring indexof


【解决方案1】:

您不能跨多行声明一个 JavaScript 字符串。你会得到一个语法错误。

SyntaxError: 未终止的字符串文字

备选方案包括:

转义换行符:

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 ); ?>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2014-09-23
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多