簡體   English   中英

查找字符串中字符的第二次出現

[英]Find second occurrence of a character in a string

我聽說JavaScript具有一個名為search()的函數,該函數可以在另一個字符串(B)中搜索一個字符串(讓我們稱之為A),它將返回在B中找到A的第一個位置。

var str = "Ana has apples!";
var n = str.search(" ");

代碼應返回3作為在str中找到空格的第一個位置。

我想知道是否有一個函數可以在字符串中找到下一個空格。

例如,我想找到字符串中第一個單詞的長度,如果我知道它的開始位置和結束位置,就可以輕松地做到這一點。

如果有這樣的功能,那么有沒有比這更好的功能了?

您需要使用String.indexOf方法。 它接受以下參數:

str.indexOf(searchValue[, fromIndex])

因此,您可以執行以下操作:

 var str = "Ana has apples!"; var pos1 = str.indexOf(" "); // 3 var pos2 = str.indexOf(" ", pos1 + 1); // 7 console.log(pos2 - pos1 - 1); // 3... the result you were expecting 

.indexOf(…)將使您首次出現" " (從0開始):

 var str = "Ana has apples!"; var n = str.indexOf(" "); console.log(n); 

如果您希望所有事件都發生,可以使用RegExp一段while來輕松實現:

 var str = "Ana has apples! A lot."; var re = new RegExp(" ","ig"); var spaces = []; while ((match = re.exec(str))) { spaces.push(match.index); } // Output the whole array of results console.log(spaces); // You can also access the spaces position separately: console.log('1st space:', spaces[0]); console.log('2nd space:', spaces[1]); 


⋅⋅⋅

或者……您可以使用do {} while ()循環:

 var str = "Ana has apples! A lot."; var i = 0, n = 0; do { n = str.indexOf(" "); if (n > -1) { i += n; console.log(i); str = str.slice(n + 1); i++; } } while (n > -1); 

然后,您可以對其進行以下操作:

 var str = "Ana has apples! A lot."; // Function function indexsOf(str, sub) { var arr = [], i = 0, n = 0; do { n = str.indexOf(" "); if (n > -1) { i += n; arr.push(i); str = str.slice(n + 1); i++; } } while (n > -1); return arr; } var spaces = indexsOf(str, ' ') // Output the whole array of results console.log(spaces); // You can also access the spaces position separately: console.log('1st space:', spaces[0]); console.log('2nd space:', spaces[1]); 


⋅⋅⋅

希望能幫助到你。

匹配更好的是使用regex 有使用組'g'標志的匹配組之類的選項

 var str = "Ana has apples !"; var regBuilder = new RegExp(" ","ig"); var matched = ""; while((matched = regBuilder.exec(str))){ console.log(matched + ", position : " +matched.index); } str = "Ana is Ana no one is better than Ana"; regBuilder = new RegExp("Ana","ig"); while((matched = regBuilder.exec(str))){ console.log(matched + ", position : " +matched.index); } 


'i'標志用來忽略大小寫您也可以在這里檢查其他標志

嘗試這個:

 const str = "Ana has apples!"; const spaces = str.split('') .map((c, i) => (c === ' ') ? i : -1) .filter((c) => c !== -1); console.log(spaces); 

然后,您將所有空格位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM