I am currently working on a function to search for a specific substring within a given string.
// the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
var test = "1~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function findValue(test, stringIndex) {
// the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
// need help with this.
// I can only retrieve the value if 1 is the parameter passed, here is the code:
return test.replace(new Regexp(stringIndex + '\~(.+?(?=\|)).+'), '$1');
}
// example usage:
findValue(test, '1'); // returns 'abc1', even though there are two 1's
findValue(test, '4'); // returns 'jk-14'
findValue(test, '6'); // returns 'sj2j'
findValue(test, '123213'); // returns ''
Essentially, I am creating a function that takes both the test
string and the stringIndex
as parameters, then searches the test
string using the provided stringIndex
and returns the associated value. The format of the test string is outlined in the comments above. I am specifically seeking a regex solution without utilizing loops or split methods.