Alternative way for JavaScript string manipulation
JavaScript
document.write('<h2>repeat:</h2>');
function repeat(str, n) {
var arr = new Array(n+1);
return arr.join(str);
}
document.write(repeat('-', 7));
document.write('<h2>prototype repeat:</h2>');
String.prototype.repeat = function(n) {
var arr = new Array(n+1);
return arr.join(this);
};
document.write(repeat('-', 7));
document.write('<h2>Array as StringBuilder:</h2>');
var sb = [];
for(var i = 0; i <=21; i++) {
sb.push(i);
}
document.write(sb.join(''));
document.write('<h2>split for substr:</h2>');
function getBaseName(str) {
var segs = str.split('.');
if(segs.length > 1) segs.pop();
return segs.join('.');
}
function getExtension(str) {
var segs = str.split('.');
if(segs.length <= 1)return '';
return segs.pop();
}
var fileName = 'hello_world.js';
document.write(getBaseName(fileName));
document.write('<br />');
document.write(getExtension(fileName));
document.write('<h2>split for replace:</h2>');
var str = 'hello_from_ider_to_world'.split('_').join('-');
document.write(str);
document.write('<h2>RegExp replace with Back Reference:</h2>');
var friends = 'friends of Ider, friend of Angie';
var result = friends.replace(/(friends?) of (\w+)/g, "$2's $1");
document.write(result);
document.write('<h2>replace with Function:</h2>');
friends ="friends of mine, friend of her and friends of his";
result = friends.replace(/(friends?) of (\w+)/g,
function($0, $1, $2) {
if($2 == 'mine') $2 = 'my';
return $2 + ' ' + $1;
});
document.write(result);
document.write('<h2>Expression in switch case</h2>');
function whereIsIder(s) {
var result = '';
switch(true) {
case s == 'Ider':
result = ' is Ider';
break;
case /^Ider/.test(s):
result = ' starts with Ider';
break;
case /Ider$/.test(s):
result = ' ends with Ider';
...