其中一個(不同於其他答案)的可能性將是使用Regular Expressions - 這樣,你也靈活,應該在文字前電話改變長度。您需要:
使用常規的串碼錶達式可以是這樣的:
var input = "170 West Tasman Drive San Jose, CA 95134 United States - Phone: 408-526-4000 Website:";
var regExPattern = /Phone:/; // the expression that is matched against
var cutPosition = input.search(regExPattern); // find the start position of the word by searching a match
if (cutPosition != -1) {
var text = input.substring(0, input.search(regExPattern));
// do something with the text
}
IMO使用正則表達式在這種情況下,可以使任務更容易 - 也有鄰
var input = "170 West Tasman Drive San Jose, CA 95134 United States - Phone: 408-526-4000 Website:";
var regExPattern = /Phone:.*/; // the expression that is matched against - now it is Phone: and everything after
var text = input.replace(regExPattern, ""); // replace Phone: and everything after with empty string
// do something with text
假設:ption使用string.replace method刪除文本(從手機開始:)一次在一行文字電話:始終存在!
如果輸入內部沒有出現「電話」,該怎麼辦? – Jon