1

I'm using stringformat library to format strings in node.js.

var stringFormat = require('stringformat');
stringFormat.extendString();

I'm trying to pass along an array of parameters instead inline, like this:

var formatted = '{0}{1}'.format(params);

Instead of :

var formatted = '{0}{1}'.format(params[0], params[1]);

But the library doesn't support this.

I've followed this question: nodejs-util-format-passing-an-array And tried this:

params.unshift('{0}{1}');
String.prototype.format.apply(String.prototype, params);

And also:

var i = -1;
'{0}{1}...'.format(function() {
    i++;
    return params[0];
});

And none of them worked as expected.

Any ideas?

3
  • 1
    may be you can try var formatted = '{0}{1}'.format(...params); Commented Jun 5, 2016 at 7:25
  • What's the ... ? Commented Jun 5, 2016 at 7:30
  • It's the ES6 functionality the spread operator. It's ideal for this case. Commented Jun 5, 2016 at 7:30

2 Answers 2

1

Or if you don't want to use the spread operator as i have mentioned in the comment you can also do something like this in ES5;

function formatWithArray(str,arr){
var a = arr[0],
    b = arr[1],
    c = arr[2],
    d = arr[3];
return str.format(a,b,c,d);
}
var formatted = formatWithArray('{0}{1}',params);

Should work fine up to 4 parameters though in your particular case the last two (c and d) will be undefined. I hope the stringFormat library won't bother with excess parameters.

Sign up to request clarification or add additional context in comments.

Comments

1

you can write your own format extension like this:

String.prototype.myFormatString = function(_array){
    var s = _array[0];
    for (var i = 0; i < _array.length - 1; i++) {       
         var reg = new RegExp("\\{" + i + "\\}", "gm");             
         s = s.replace(reg, _array[i + 1]);
    }
    return s;
}

and call it in your code:

var formatted = '{0}{1}'.myFormatString(params);

hope that helps.

1 Comment

s.replace(reg, arguments[i + 1]); should be s.replace(reg, Array[i + 1]);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.