function vsprintf(str, arr)
{
function vprint(match, part)
{
// though without type checking ...
return arr[part - 1];
}
// though I'd rather go for %1 than 1:
return str.replace(/(\d):/g, vprint);
}
__________________
please post your code wrapped in [CODE] [/CODE] tags
Last edited by Dormilich; 10-19-2010 at 02:02 PM..
Reason: some improvements
If the string had a double digit before column eg 11: . The function returned
names[1-1] ; instead of names[11-1]; So code limited to between 1 to 9;
Also if it was a stringwith 10: it would cos an error cos it would try to return names[0-1];
so made some modifications to cater for this situations. also if the array position is undefined, it should return the matched pattern back.
function vsprintf(str, arr)
{
function vprint(match, part)
{
// though without type checking ...
if(part>=1 && part<=arr.length){
//IF part is 0 and not greater than array length,
var h=arr[part - 1];
}
if(!h){//IF h is undefined return the match pattern back
h=part+':'; //just precaution. shouldnt be necessary
}
return h;
}
// though I'd rather go for %1 than 1: (WHAT IS THE REGEX FOR THIS)
return str.replace(/(\d):/g, vprint);
}
var str= "1: said that there are 10 kings in 13:'s house. Tell 4: to come 10: quickly and bring gifts as well."
var names=new Array('ben','chris','mary','john','jane','keisha','ellan','joise','bukky','janet','christopher');
var str2=vsprintf(str, names);
document.write(str2);
printed to screen
"ben said that there are 10 kings in 1mary's house. Tell john to come 10: quickly and bring gifts as well."
Would love it if it could match double digits as well. but i guess this is sufficient thanks.
Actually %1 maybe better. but it should also match %12 (the double digit).
So what is the code for matching %1 and %12 instead.
So matching all digits attached to special character
// though I'd rather go for %1 than 1: (WHAT IS THE REGEX FOR THIS)
/%(\d+)/g
Quote:
Originally Posted by barnabas1
so made some modifications to cater for this situations. also if the array position is undefined, it should return the matched pattern back.
Code:
function vprint(match, part)
{
// though without type checking ...
if(part>=1 && part<=arr.length){
//IF part is 0 and not greater than array length,
var h=arr[part - 1];
}
if(!h){//IF h is undefined return the match pattern back
h=part+':'; //just precaution. shouldnt be necessary
}
return h;
}
if(!h) will also fire if h is null, 0 or "". better use
Code:
function vprint(match, part)
{
if(part > 0 && part <= arr.length) {
//IF part is 0 and not greater than array length,
return arr[part - 1];
}
return match; // preferably return ""; (more consistent with the expectations)
}
__________________
please post your code wrapped in [CODE] [/CODE] tags
Last edited by Dormilich; 10-20-2010 at 07:21 AM..