1. 程式人生 > >JavaScript 格式化字串 & 需要轉義的正則表示式

JavaScript 格式化字串 & 需要轉義的正則表示式

<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<script>
String.prototype.format = function() {
	let result = this;
	console.log(arguments)
	if(arguments.length == 1 && typeof(arguments[0]) == "object") {
		for(let key in arguments[0]) {
			let reg = new RegExp("{" + key + "}", "g");
			result = result.replace(reg, arguments[0][key]);
		}
	} else if(arguments.length > 0 ) {
		for (let i = 0; i < arguments.length; i++) {
			if(arguments[i] != undefined) {
				//注意:花括號內跟數字表示前面的字元出現多少次。因此這裡需要轉義,而在字串裡面,轉義字元又要多重複一次
				let reg = new RegExp("\\{" + i + "\\}", "g");
				result = result.replace(reg, arguments[i]);
			}
		};
	}
	return result;
}
console.log("The boy's name is {name}, and age is {age}.".format({name: "bob", age: 24}));
console.log("The boy's name is {0}, and age is {1}.".format("bob", 24));
</script>
</head>
<body>

</body>
</html>