Reputation: 345
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.
Upvotes: 0
Views: 72
Reputation: 66
Here is an update for the above two answers, we need to add "\b" for the regexp.
// modified the test string.
var test = "311~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function getValue(test, stringIndex) {
var m = test.match(new RegExp("\\b" + stringIndex + "~([^|]+)", 'i')) || [null, null];
return m[1];
}
> getValue(test, '1');
'ghi3'
> getValue(test, '2');
'def2'
> getValue(test, '11');
null
> getValue(test, '311');
'abc1'
Upvotes: 1
Reputation: 13828
There are plenty ways of writing regular expression for matching a pattern, it really depends on the specificity of your use case. Here is one solution:
var test = "1~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function getValue(test, stringIndex) {
var matches = test.match(new RegExp(stringIndex + "~([\\w-]+)\\|?"));
return matches ? matches[1] : "";
}
getValue(test, '1'); // 'abc1'
getValue(test, '4'); // 'jk-14'
getValue(test, '6'); // 'sj2j'
getValue(test, '123213'); // ''
Upvotes: 0
Reputation: 784898
You probably want this regex code:
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:
var m = test.match(new RegExp(stringIndex + "~([^|]+)", 'i')) || [null, null];
return m[1];
}
Then calling it as:
getValue(test, '1');
"abc1"
getValue(test, '4');
"jk-l4"
getValue(test, '6');
"sj2j"
getValue(test, '123213');
null
Upvotes: 1