簡體   English   中英

如何獲取javascript中特殊字符所在的第一個和最后一個單詞或字符?

[英]How can I get the first and the last word or character between which a special character fall in javascript?

讓我們考慮一個名為calc的字符串,它定義為:

const calc = "Find 2&3";

現在有一個名為parse()的函數,它執行如下操作:

console.log( parse(calc) );
// => First character is 2 while last character is 3 

所以,我們觀察到parse()函數計算出&落在的第一個和最后一個字符。 那么,可以制作parse()嗎? 如果是怎么辦? 如果沒有其他選擇? 如果有多個呢?

例如

const calc = "Find 2&3 , 4&5 , 6&7";
console.log( parse(calc) );
// => First character is 2 while last character is 3 
// => First character is 4 while last character is 5
// =>  First character is 6 while last character is 7 

您可以使用帶有正則表達式的String.match()來匹配第一個字符和最后一個字符,它們不是空格( \\S )並且它們之間有& (更多信息在regex101 )。

注意:匹配的結果是一個包含匹配字符串的數組,兩個捕獲組的結果。 我使用解構將它們分配到firstlast

 const calc = 'Find 2&3'; const [, first, last] = calc.match(/(\\S)\\S*&\\S*(\\S)/); console.log(first, last);

要獲取所有匹配項,您可以使用String.matchAll() (IE 或 Edge 不支持)。 結果將是一個迭代器,您可以將其擴展到包含帶有結果的子數組的數組。

 const calc = 'Find 2&3 , 4&5 , 6&7'; const matches = calc.matchAll(/(\\S)\\S*&\\S*(\\S)/g); console.log([...matches]);

暫無
暫無

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

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