字符串 search() 方法
search() is method 是一個 String 方法,用於檢查給定字符串中是否存在子字符串。它從子字符串所在的字符串返回子字符串的起始索引。如果字符串中不存在子字符串 – 則返回 -1。
用法:
String.search(substring);
這裏,substring
是要搜索的字符串的一部分。
例:
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var str = "friends say Hello";
var substr = "Hello";
var index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
</script>
</body>
</html>
輸出
Hello found at 12 position. Hi does not exist in the friends say Hello.
相關用法
- JavaScript String slice()用法及代碼示例
- JavaScript String substr()用法及代碼示例
- JavaScript String substring()用法及代碼示例
- JavaScript String repeat()用法及代碼示例
- JavaScript String charCodeAt()用法及代碼示例
- JavaScript String endsWith()用法及代碼示例
- JavaScript String charAt()用法及代碼示例
- JavaScript String normalize()用法及代碼示例
- JavaScript String matchAll()用法及代碼示例
- JavaScript String valueOf()用法及代碼示例
- JavaScript String toLocaleUpperCase()用法及代碼示例
- JavaScript String toLocaleLowerCase()用法及代碼示例
- JavaScript String fromCharCode()用法及代碼示例
- JavaScript String concat()用法及代碼示例
- JavaScript String includes()用法及代碼示例
- JavaScript String toString()用法及代碼示例
- JavaScript String replace()用法及代碼示例
- JavaScript String match()用法及代碼示例
- JavaScript String toUpperCase()用法及代碼示例
- JavaScript String lastIndexOf()用法及代碼示例
注:本文由純淨天空篩選整理自 String search() Method with Example in JavaScript。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。