标签: javascript es6
字符串新增特性
- 新增二个方法 - startsWith/endsWith
- 字符串模板 - 反单引号的应用
startsWith
判断字符串以是否以某某开头,返回一个布尔值
示例代码如下:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>startsWith</title><script type="text/javascript">//判断一个网址的类型function judgeUrl(str){if(str.startsWith('http://')){console.log(str+':这是个普通网址');}else if(str.startsWith('https://')){console.log(str+':这是个加密网址');}else if(str.startsWith('git://')){console.log(str+':这是个git地址');}else if(str.startsWith('svn://')){console.log(str+':这是个SVN地址');}else{console.log('其它!');}}</script>
</head>
<body><button onclick="judgeUrl('http://www.baidu.com');">http://www.baidu.com</button><button onclick="judgeUrl('https://www.baidu.com');">https://www.baidu.com</button><button onclick="judgeUrl('git://www.baidu.com');">git://www.baidu.com</button><button onclick="judgeUrl('svn://www.baidu.com');">svn://www.baidu.com</button><button onclick="judgeUrl('htdfdfdfdf');">http://www.baidu.com</button>
</body>
</html>
测试地址
endsWith
判断字符串以是否以某某结束,返回一个布尔值
示例代码如下:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>endsWith</title><script type="text/javascript">//判断一个网址的类型function judgeUrl(str){if(str.endsWith('.jpg')){console.log(str+':这是jpeg格式图片');}else if(str.endsWith('.png')){console.log(str+':这是png格式图片');}else if(str.endsWith('.gif')){console.log(str+':这是gif格式图片');}else if(str.endsWith('.bmp')){console.log(str+':这是bmp格式图片');}else{console.log('其它!');}}</script>
</head>
<body><button onclick="judgeUrl('aaa.jpg');">aaa.jpg</button><button onclick="judgeUrl('aaa.png');">aaa.png</button><button onclick="judgeUrl('aaa.gif');">aaa.gif</button><button onclick="judgeUrl('aaa.bmp');">aaa.bmp</button><button onclick="judgeUrl('aaa.doc');">aaa.doc</button>
</body>
</html>
测试地址
字符串模板
- 可以直接把变量插入到字符串里面
- 折行不必做特殊处理
示例代码如下:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>字符串模板</title>
</head>
<body><h3>字符串方式</h3><div id="test1"></div><hr /><h3>\方式</h3><div id="test2"></div><hr /><h3>ES6字符串模板方式</h3><div id="test3"></div><script>var title = "这是标题";var content = "这里是内容,应该放的内容!!";//第一种字符串拼接方法var htmlStr0 = "<div>"+"<h4>"+title+"</h4>"+"<p>"+content+"</p>"+"</div>";//第二种字符串拼接方法var htmlStr1 = "<div>\<h4>"+title+"</h4>\<p>"+content+"</p>\</div>";//es6字符串模板方法var htmlStr2 = `<div><h4>${title}</h4><p>${content}</p></div>`;document.getElementById('test1').innerHTML = htmlStr0;document.getElementById('test2').innerHTML = htmlStr1;document.getElementById('test3').innerHTML = htmlStr2;</script></script></script>
</body>
</html>
测试地址