var s = "JavaScript"; var i = s.indexOf("a"); console.log(i); //返回值为1,即字符串中第二个字符
数字转字符串
NumberObject.toString(radix)
多行字符串
ES6 的有一个新的特性,Template Strings, 这是语言层面上第一次实现了多行字符串
var tmpl = `!!! 5 html include header body //if IE 6 .alert.alert-error center 对不起,我们不支持IE6,请升级你的浏览器 a(href="http://windows.microsoft.com/zh-CN/internet-explorer/download-ie") | IE8官方下载 a(href="https://www.google.com/intl/en/chrome/browser/") | Chrome下载 include head .container .row-fluid .span8 block main include pagerbar .span4 include sidebar include footer include script`
var tmpl = heredoc(function(){/* !!! 5 html include header body //if IE 6 .alert.alert-error center 对不起,我们不支持IE6,请升级你的浏览器 a(href="http://windows.microsoft.com/zh-CN/internet-explorer/download-ie") | IE8官方下载 a(href="https://www.google.com/intl/en/chrome/browser/") | Chrome下载 include head .container .row-fluid .span8 block main include pagerbar .span4 include sidebar include footer include script */});
字符串切片
stringObject.slice(start,end) var newStr = dt.slice(2,4); // 去掉尾部的一个字符 newStr = dt.slice(0,-1);
字符串插入
//插入 参数说明:str表示原字符串变量,flg表示要插入的字符串,sn表示要插入的位置 functionstr_insert(src, insertStr, pos) { var newStr = ""; for (var i = 0; i < src.length; i += pos) { var tmp = src.substring(i, i + pos); newStr += tmp + insertStr; } return newStr; }
格式化
/** * 替换所有匹配exp的字符串为指定字符串 * @param exp 被替换部分的正则 * @param newStr 替换成的字符串 */ String.prototype.replaceAll = function (exp, newStr) { returnthis.replace(newRegExp(exp, "gm"), newStr); }; /** * 原型:字符串格式化 * @param args 格式化参数值 */ String.prototype.format = function(args) { var result = this; if (arguments.length < 1) { return result; } var data = arguments; // 如果模板参数是数组 if (arguments.length == 1 && typeof (args) == "object") { // 如果模板参数是对象 data = args; } for ( var key in data) { var value = data[key]; if (undefined != value) { result = result.replaceAll("\\{" + key + "\\}", value); } } return result; }
//两种调用方式 var template1="我是{0},今年{1}了"; var result1=template1.format("loogn",22); var template2="我是{name},今年{age}了"; var result2=template2.format({name:"loogn",age:22}); //两个结果都是"我是loogn,今年22了" var template1="我是{0},今年{1}了, lucy今年也{1}了"; var result1=template1.format("loogn",22); //结果是"我是loogn,今年22了, lucy今年也22了"