如何在JavaScript中根据字符的位置提取子字符串

How to extract substring based on position of a character in JavaScript?

本文关键字:位置 提取 字符串 字符 JavaScript      更新时间:2023-09-26

我有一个字符串,如下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]); 

这应该有效(在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>

试试这个

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