Reputation: 6650
I have a String as following Jack_XX3_20 , I need to retrieve 20 based on position of XX3. I am using following code but it returns 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>
Upvotes: 0
Views: 863
Reputation: 21961
Try this
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;
}
Upvotes: 0
Reputation: 33628
Something like this ?
str.substring(str.indexOf("XX3")+4, str.length)
This is how you want to use substring
str.substring(indexA[, indexB])
indexA
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.
Source: mdn
UPDATE
You are looking for a regex based on the comment
var str = "Jack_XX3_24930YYYG";
var reg = /XX3_(\+?\d+)/g;
var match = reg.exec(str);
alert(match[1]);
Upvotes: 4
Reputation: 123
This should work(Tested in 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>
Upvotes: 0