codecamp

CoffeeScript 拆分字符串

拆分字符串

问题

你想拆分一个字符串。

解决方案

使用JavaScript字符串的split()方法:

"foo bar baz".split " "
# => [ 'foo', 'bar', 'baz' ]

讨论

String的这个split()方法是标准的JavaScript方法。可以用来基于任何分隔符——包括正则表达式来拆分字符串。这个方法还可以接受第二个参数,用于指定返回的子字符串数目。

"foo-bar-baz".split "-"
# => [ 'foo', 'bar', 'baz' ]
"foo   bar  \t baz".split /\s+/
# => [ 'foo', 'bar', 'baz' ]
"the sun goes down and I sit on the old broken-down river pier".split " ", 2
# => [ 'the', 'sun' ]
CoffeeScript 重复字符串
CoffeeScript 清理字符串前后的空白符
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CoffeeScript 数据库

关闭

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; }