codecamp

Node.js 字符串函数

indexOf

要查找具有另一个字符串的字符串,请使用 indexOf 函数:

var i = "this is a test".indexOf("is");
console.log(i);

上面的代码生成以下结果。

indexOf函数结果

substr和splice

要从字符串中提取子字符串,请使用 substr splice 函数。

substr 获取要提取的字符串的起始索引和长度。 splice 取起始索引和结束索引:

var s = "this is a test string.".substr(19, 3);
var s1 = "this is a test string.".slice(19, 22);
console.log(s);
console.log(s1);

上面的代码生成以下结果。

substr和splice结果

Split

要将字符串拆分为子字符串,请使用split函数并获取数组作为结果:

var s = "a|b|c|d|e|f|g|h".split("|");
console.log(s);

上面的代码生成以下结果。

split函数结果

Javascript V8 函数中的trim函数从字符串的开头和结尾删除空格:

var s = "       cat   \n\n\n    ". trim();
console.log(s);
Node.js 字符串
Node.js 对象
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }