How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

Question!

I need to break a string apart after certain characters.

document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + "  <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;




 function Chest(id){
    window.open('LootGen.html', '_blank');
 }
 function Combat(id){
    document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
 }

When this runs the value that results is:

|+HP:+20

However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:

var parameters = location.search.substring(1).split("&");

This doesn't work here for some reason as first of all the var is an innher html. Could someone please point me in the write direction as I'm not very good at reading docs.



Answers

using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".

Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1

function Combat(id){
    var vaultInner = document.getElementById("vault" + id).innerHTML;
    document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}


the code example using the split would give you an array of stuff separated by the plus

function Combat(id){
    //splits into an array
    var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
    //returns last element
    document.getElementById("C").value = vaultInner[vaultInner.length -1];
}


var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();

References:

By : Ouroborus


This video can help you solving your question :)
By: admin