Javascript两个小巧的自定义字符串格式化函数
document.close();
document.open();
function jsonFormat(template, json) {
return template.replace(/\$\{(.+?)\}/g, function ($, $1) {
return json[$1];
});
}
var links = [
{ text: "人肉搜索", url: "http://renrousousuo.com" } ,
{ text: "CSDN", url: "http://www.csdn.net" } ,
{ text: "谷歌", url: "http://g.cn" } ,
{ text: "百度", url: "http://www.baidu.com" }
];
for (var i = 0; i < links.length; i++) {
document.write(
jsonFormat('<a href="${url}" mce_href="${url}" target="_blank">${text}</a><br/>', links[i])
);
}
function strFormat(template/*, ...*/) {
var arg = arguments;
return template.replace(/\{(\d+)\}/g, function ($, $1) {
return arg[+$1 + 1];
});
}
document.write(strFormat("<b>{0}</b> <i>{1}</i>!", "zswang", "路过"))
使用字符串格式化函数有什么好处?
在实际工作中,代码的可读性很重要,易读的代码可以减轻维护工作量。
格式化代码不仅可以提高可读性,还有扩展性。
没有使用格式化的代码:
'<a href="' + json.url + '" mce_href="' + json.url + '" target="_blank">' + json.text + '</a><br/>'
当字符串需要拼接的次数更多时,代码可读性将降低。
相关文档:
6、基于对象的JavaScript语言
JavaScript是基于对象的的语言,不像面向对象有抽象、继承、重载等有关面向对象的功能,但是它还是具有面向对象的基本特征,它可以根据需要创建自己的对象,从而进一步扩大JavaScript的应用范围,增强编写功能强大的Web文档。
对象的基础知识:
对象是由属性和方法两个基本元素组成。一个对 ......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js除去字符串空格 ......
Java代码 import flash.external.ExternalInterface; function hello(){ return "测试成功了哦~~"; } //允许flash调用js函数 参数1:js函数名称 参数2:向js函数传递的参数 ExternalInterface.call("hello", "jacky"); ......
文章分类:
JavaScript
文章标题:
javascript 字符串处理全攻略
关 键 字:
0
文章作者:
alonglee
文章来源:
http://lmgq.vip.sina.com/tech/jsadvancedlesson/c2p1.htm
发表时间:
2004-9-21 14:43:00
一、声明字符串:
var normal_monkey = "I&n ......
1. oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键
<table border oncontextmenu=return(false)> <td>no </table> 可用于Table
2. <body onselectstart="return false"> 取消选取、防止复制
3. onpaste="return false" 不准粘贴
4. oncopy ......