【发布时间】: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"><td class="views-field views-field-line-item-title">');
但它没有返回一个有效的整数位置,它实际上没有返回任何东西......我想知道我做错了什么以及我最好如何解决这个问题。
谢谢!
【问题讨论】:
-
检查你的开发者控制台。看起来您有语法错误。具体来说,一个跨多行的字符串。
-
@AlexanderO'Mara 我绝对愿意,您是说跨多行的字符串在 javascript 中无效吗? :o
-
是的,出于某种原因,这是设计决定。
-
@AlexanderO'Mara 那么我有什么替代品吗?
-
如果它来自像 PHP 这样的服务器端脚本语言,请使用 JSON 编码器对其进行编码。如果没有,check out this question 和 this question。
标签: javascript find substring indexof