I am trying to search for a substring on a given string.
// format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
var test = "1~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function getValue(test, stringIndex) {
// format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
//help with this.
//I can only get the value if 1 is the passed parameter, here is the code:
return test.replace(new Regexp(stringIndex + '\~(.+?(?=\|)).+'), '$1');
}
// usage:
getValue(test, '1'); //returns 'abc1', even though there are two 1's
getValue(test, '4'); //returns 'jk-14'
getValue(test, '6'); //returns 'sj2j'
getValue(test, '123213'); // returns ''
Basically, I'm writing a function which accepts the test string and stringIndex as a parameter, and searches the test string using that stringIndex and return the value associated with it. the format of the test string is stated above in the comments.
I'm only looking for regex solution without using loops or split.
gflag on your regex to do a global replace.stringIndex