This project is archived and is in readonly mode.

#640 ✓wontfix
Kai Gülzau

String.substitute() proposal: recursive + hash friendly

Reported by Kai Gülzau | April 20th, 2009 @ 10:45 AM | in 2.0 (closed)

In my code i often use substitute as a simple template mechanism. I've extended the original code to allow:

1.) recursive substitution 2.) hash/object/array access


String.implement({
substitute: function(object, regexp){
		return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
			if (match.charAt(0) == '\\') return match.slice(1);
			var parts = name.split('.');
			var val = object;
			for(var i=0; i < parts.length && ($type(val) == 'object' || $type(val) == 'hash' || $type(val) == 'array'); i++)
				val = val[parts[i]];
			return val == undefined ? '' : $type(val) == 'string' ? val.substitute(object, regexp) : val;
		});
	}
}, true);

Examples: 1.) var data = {replacement: 'foo {beer}', beer: 'bar'}; alert("This is {replacement}".substitute(data));

2.) var data = {msg: {foo: 'bar'}}; alert("This is {msg.foo}".substitute(data));

3.) combined var data = {msg: {foo: '{msg.bar}', bar: ['beer', 'foo bar']}}; alert("This is {msg.foo.1}".substitute(data));

open issues: - performance tests - endless recursion - backwards compatibility broken (due to recursion)

regards, Kai Gülzau

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Shared Ticket Bins

People watching this ticket

Pages