我有一个字符串,如下 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>
最佳答案
类似这样的事情吗?
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.
索引B
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]);
关于javascript - 如何根据JavaScript中字符的位置提取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28893440/