Skip to content

Instantly share code, notes, and snippets.

@yangg
Created December 17, 2011 10:18
Show Gist options
  • Save yangg/1489875 to your computer and use it in GitHub Desktop.
Save yangg/1489875 to your computer and use it in GitHub Desktop.
String Buffer Class for Javascript
/*!
* StrBuf: A javascript string buffer class
* @author uedsky (http://uedsky.com)
* Last Modified: Dec 17, 2011
*/
/**
* @class String concat
* @return {StrBuf/String}
* @constructor
* eg:
var buf = new StrBuf("contructor str<br/>");
buf.push("hello,<br/>")
.push("Today is {0}, {1}<br/>", "Monday", "March 28th")
.push("I like ${like}, my name is ${name}, my qq is ${im.qq}, msn is ${im.msn}", {
like: "Vim",
name: "yang",
im: {qq: '999999', msn: 'me@live.cn'}
});
document.write(buf);// auto call toString method
console.log(buf);
console.log(StrBuf("static {0} method", "invoke"));
*/
function StrBuf(s) {
this.__data = [];
if(s) {
var args = arguments, buf;
if(this instanceof StrBuf) {
this.push.apply(this, args);
} else {// static invoke
buf = new StrBuf();
return buf.push.apply(buf, args).toString();
}
}
}
StrBuf.prototype = {
/**
* add String to the instance
* @return StrBuf make it chainability
*/
push: function(s, /*{Object/String...} */o, _undef) {
var args = arguments, str;
if(args.length < 2) {
str = s === undefined ? '' : s;
} else if(typeof o == 'object') {
str = s.replace(/\$\{([\w.]+)\}/g, function($, $1) {
var parts = $1.split('.'), i = 0, len = parts.length, res = o;
while(i < len) {
try {
res = res[parts[i++]];
} catch(ex){
res = $;
}
}
return res === undefined ? _undef : res;
});
} else {
str = s.replace(/\{(\d+)\}/g, function($, $1) {
return args[+$1 + 1];
});
}
this.__data.push(str);
return this;// chainability
},
/**
* get the final string
* @param {String} delimiter default to ''(empty string)
*/
toString: function(delimiter) {
return this.__data.join(delimiter === undefined ? '' : delimiter);
}
};
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
</body>
<script src="strbuf.js"></script>
<script>
var buf = new StrBuf("contructor str<br/>");
buf.push("hello,<br/>")
.push("Today is {0}, {1}<br/>", "Monday", "March 28th")
.push("I like ${like}, my name is ${name}, my qq is ${im.qq}, msn is ${im.msn},<br/>${test.test2.son}, ${test.test2.daughter}", {
like: "Vim",
name: "yangg",
im: {qq: '999999', msn: 'me@live.cn'},
test: { test2: {son:'test grand son', daughter: 'test grand daughter'}}
});
document.write(buf);// auto call toString method
console.log(buf);
console.log(StrBuf("static {0} method", "invoke"));
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment