我需要您的幫助,查明一個字符串中是否存在匹配
使用javascript,如何找出匹配是否在字符串中?
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
所以,我需要一個函數,讓我檢查價值y對價值x。
值來搜索:
y = "PEAR"
if (y matches the string in x) then return true
我需要您的幫助,查明一個字符串中是否存在匹配
使用javascript,如何找出匹配是否在字符串中?
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
所以,我需要一個函數,讓我檢查價值y對價值x。
值來搜索:
y = "PEAR"
if (y matches the string in x) then return true
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
y = "PEAR"
// Checks if string x having string y
if(x.includes(y)) { console.log("MATCH FOUND"); return true; }
// Returns index of string y in x , -1 if not present
if(x.indexOf(y) > -1) { console.log("MATCH FOUND"); return true; }
有這樣做的許多方面。請閱讀Javascript字符串對象的文檔
的
indexOf()
方法返回指定值的第一次出現的調用String對象的索引,開始的fromIndex搜索。如果未找到該值,則返回-1
。
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON",
y = "PEAR";
console.log(x.indexOf(y) !== -1); //If true, exist
你嘗試過什麼?我的意思是,JavaScript確實有['includes'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)方法... –
@MikeMcCaughan,[ '.includes()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)目前是一個不好的建議。它最近被添加到JavaScript中,並且[在較舊的瀏覽器(例如IE,Opera)中受到限制/不支持](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String /包括#Browser_compatibility)。在幾年/幾年內,它會很好用。現在['.indexOf()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf)將是更好的建議。 – Makyen
@Makyen。這是一條評論,而不是一個答案。此外,該瀏覽器支持鏈接已過時。請參閱[此列表](http://kangax.github.io/compat-table/es6/#test-String.prototype_methods_String.prototype.includes)以獲取更多更新列表。也就是說,我的評論主要是關於讓OP在詢問之前嘗試一些事情,但是由於他們現在因爲缺乏研究而被授予答案,因此它有點沒有實際意義。 –