CoffeeScript攻略3.4:查詢子字串

CoffeeScript Cookbook發表於2011-11-23

問題

你想在一條訊息中查詢某個關鍵字第一次或最後一次出現的位置。

方案

分別使用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

# 修改start引數
message.indexOf "This", 5
# => 23

message.lastIndexOf "This"
# => 49

討論

還需要想辦法統計出給定字串在一條訊息中出現的次數。


enter image description here

相關文章