我有一个字符串跟随Jack_XX3_20,我需要根据XX3的位置检索20。我使用以下代码,但它返回k_XX3
<!DOCTYPE html>
<html>
<body>
<p>Test The Code</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Jack_XX3_20YYYG";
var pos = str.indexOf("XX3");
var n = str.substring(pos+3,3);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
</script>
答案 0 :(得分:2)
这样的东西?
str.substring(str.indexOf("XX3")+4, str.length)
这就是你想要使用子串的方法
str.substring(indexA [,indexB])
<强>索引A 强>
An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.
<强> indexB 强>
Optional. An integer between 0 and the length of the string, which specifies the offset into the string of the first character not to include in the returned substring.
来源:mdn
<强>更新强>
您正在根据评论
寻找正则表达式
var str = "Jack_XX3_24930YYYG";
var reg = /XX3_(\+?\d+)/g;
var match = reg.exec(str);
alert(match[1]);
&#13;
答案 1 :(得分:0)
这应该有效(在JSFiddle中测试):
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Jack_XX3_20";
var pos = str.indexOf("XX3_")+4;
var n = str.substring(pos,str.length);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
答案 2 :(得分:0)
试试这个
function myFunction() {
var str = "Jack_XX3_20qjjjj";
var pos = str.lastIndexOf("XX3_")+3;
var pos = str.indexOf("XX3_")+4;
var n = str.substring(pos,pos+2);
document.getElementById("demo").innerHTML = n;
}
<强> DEMO 强>