codecamp

CoffeeScript 查找子字符串

查找子字符串

问题

你想在一条消息中查找某个关键字第一次或最后一次出现的位置。

解决方案

分别使用JavaScript的indexOf()和lastIndexOf()方法查找字符串第一次和最后一次出现的位置。语法: string.indexOf searchstring, start

message = "This is a test string. This has a repeat or two. This might even have a third."
message.indexOf "This", 0
# => 0

# Modifying the start parameter
message.indexOf "This", 5
# => 23

message.lastIndexOf "This"
# => 49

讨论

还需要想办法统计出给定字符串在一条消息中出现的次数。

CoffeeScript 大写单词首字母
CoffeeScript 生成唯一 ID
温馨提示
下载编程狮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; }