Permalink
Browse files

adding ability to switch out delimiter

  • Loading branch information...
1 parent 39b98c1 commit 98486fe06a801ca71141a5a48d842044b66d66d2 @chadbaudoin committed Apr 12, 2012
Showing with 18 additions and 9 deletions.
  1. +16 −7 dotformat.js
  2. +2 −2 dotformat.min.js
View
@@ -17,27 +17,36 @@ if( !String.prototype.format ){
returnString = this,
replacement,
delimiter = "%",
- regex,
- key,
+ replacementRegex,
toString = Object.prototype.toString;
+ //see if the last argument is regular expression
+ if( formatArgs.length > 1 && toString.call( formatArgs[ formatArgs.length - 1 ] ) === '[object RegExp]' ){
+ //set the correct regex
+ replacementRegex = formatArgs[ formatArgs.length - 1 ];
+ //remove the regex from the format args
+ Array.prototype.pop.call(formatArgs);
+ }
+
//if there is only 1 argument and it's an array
if( formatArgs.length === 1 && toString.call(obj) === '[object Array]' ){
formatArgs = obj;
}
if( formatArgs.length === 1 && toString.call(obj) === '[object Object]' && !(obj === undefined || obj === null ) ){
- regex = new RegExp(delimiter + "[^%]*" + delimiter, "g");
- returnString = returnString.replace(regex, function(str, offset){
- key = str.replace(new RegExp(delimiter, "g"), "");
+ //object replacement
+ replacementRegex = replacementRegex || new RegExp(delimiter + "([^" + delimiter + "]*)" + delimiter, "g");
+ delimiter = replacementRegex.toString().match(/[^\\\/]/);
+ returnString = returnString.replace(replacementRegex, function(str, key){
if( obj[key] ){
return obj[key];
}
return "";
});
}else{
- regex = new RegExp(delimiter + "s", "g");
- returnString = returnString.replace(regex, function(str, offset){
+ //single argument replacement
+ replacementRegex = replacementRegex || new RegExp(delimiter + "s", "g");
+ returnString = returnString.replace(replacementRegex, function(str, offset){
replacement = formatArgs[index];
index = index + 1;
if( replacement !== undefined && replacement !== null ){
View

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

0 comments on commit 98486fe

Please sign in to comment.