我想使用纯JavaScript获取字符串中/<something>[@id
出现的最后一个索引
示例:/div[@id
或/span[@id
或/input[@id
我可以使用
获取[@id
的最后一个索引
var n = xpath.lastIndexOf("[@id");
var res = xpath.substring(n);
但我需要的是以/div[@id
/
索引
这是我将要玩的字符串示例,
示例字符串:
“/ HTML /体/格[@ ID ='PAGE- 包裹 '] /格[@ ID =' 内容 '] /格[@ ID =' centercol '] /格[@ ID =' ns_1FAHQHPMXDQ2W2ER2822_4131_Widget '] /格[@ ID =' ns_1FAHQHPMXDQ2W2ER2822_4131_ItemRow '] /格[@类=' s9OtherItems '] /格[@类=' 流体 asin s9a0'] / div [@ class ='inner'] / div [@ class ='s9hl'] / a [@ class ='title ntTitle noLinkDecoration '] /格[@类=' s9ImageWrapper '] /格[@类=' imageContainer']“
答案 0 :(得分:1)
如果没有正则表达式,结果会变得更容易:
var str = "/div[@id, /span[@id";
var lastIndex = str.lastIndexOf("[@id");
if (lastIndex !== -1) {
--lastIndex;
while (lastIndex >= 0) {
if (str.charAt(lastIndex) === "/") {
break;
}
}
}
if (lastIndex !== -1) {
console.log("Found at " + lastIndex);
}
else {
console.log("Not found");
}
答案 1 :(得分:0)
这个怎么样?
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
String.prototype.lastIndexOf = function(s) {
var index = this.reverse().indexOf(s.reverse());
return index >= 0 ? this.length - index - s.length : index;
}