Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  105] [ 5]  / answers: 1 / hits: 37090  / 13 Years ago, fri, march 25, 2011, 12:00:00

Looking for help in matching the curly brackets in a regular expression pattern.
I've tried different combinations of escapes, and symbol matching with little luck. Perhaps because it's Friday afternoon and I'm overlooking something; but your ideas would be greatly appreciated. The code below:



function stringFormat(str, arr) {
for (var i = 0; i < arr.length; i++) {
var regExp = new RegExp('^{' + i + '}$', 'g');
str = str.replace(regExp, arr[i]);
}
return str;
}

var str = '<p>The quick {0}, brown {1}</p>';

$('#test').html(stringFormat(str, ['brown', 'fox']));


I've also started a fiddle on this, http://jsfiddle.net/rgy3y/1/


More From » regex

 Answers
19

Instead of trying to match a bunch of different numbers, why not just do it all in one fell swoop:



function stringFormat(str, arr) {
return str.replace(
/{([0-9]+)}/g,
function (_, index) { return arr[index]; });
}


On your example,



var str = '<p>The quick {0}, brown {1}</p>';

// Alerts <p>The quick brown, brown fox</p>
alert(stringFormat(str, ['brown', 'fox']));


This has the benefit that nothing weird will happen if arr contains a string like '{1}'. E.g.

stringFormat('{0}', ['{1}', 'foo']) === '{1}' consistently instead of 'foo' as with the fixed version of the original, but inconsistently with stringFormat('{1}', ['foo', '{0}']) === '{0}'


[#93070] Thursday, March 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;