Reputation: 408
So I am searching a string for {x} where x is some number between 1-9 and my regexp finds the first occurrence and runs the callback function but this is only called on the first found instance. For example, {2}Some{3}String will return the replacement value x number of times depending on the integer between the brackets so the function is returning 		Some{3}
when I would like it to return 		Some			String
.
I don't know very much regexp but is there something that I need to add in-order to have the callback function executed on all matched occurrences?
Here's the code
var string = "{2}Some{3}String";
function replaceWithTabs(propertyName) {
var regExp = new RegExp('\{[1-9]\}');
function addTabs(match) {
var string = '',
i = 0,
length = match.substring(1,2);
for(i; i < length; i++) {
string += "	";
}
return string;
} return propertyName.replace(regExp, addTabs); }
Upvotes: 2
Views: 522
Reputation: 48813
Use this RegExp
literal instead:
var regExp = /{[1-9]}/g;
{
or }
is not a special symbol in Regular Expression
so you can avoid slashes. g
flag of RegExp means global match
,without that you will only replace first match,but not all matches. Using literal
instead of RegExp contstructor
is preferred, because it's faster.Also if you use RegExp constructor, you additionally need to escape \
symbols,because slash is special symbol in string literal
. Consider this:
var regliteral = /\./;
//Similar with constructor
var regconstructor = new RegExp('\\.'); //slash is special symbol in string,so we add extra slash before it
Upvotes: 3