如何使用 JavaScript 在字串中匹配多個出現?


若要匹配字串中的多個出現,請使用正則表示式。以下為程式碼: −

示例

function checkMultipleOccurrences(sentence) {
   var matchExpression = /(JavaScript?[^\s]+)|(typescript?[^\s]+)/g;
   return sentence.match(matchExpression);
}
var sentence="This is my first JavaScript Program which is the subset
of typescript";
console.log(sentence);
console.log(checkMultipleOccurrences(sentence));

若要執行上述程式,您需要使用以下命令: −

node fileName.js.

在此,我的檔名為 demo70.js。

輸出

這將產生以下輸出: −

PS C:\Users\Amit\JavaScript-code> node demo70.js
This is my first JavaScript Program which is the subset of typescript
[ 'JavaScript', 'typescript' ]

更新時間:07-9-2020

1K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.