亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
Using flags for more flexibility
Capturing and grouping with parentheses
Replacing text dynamically with $1 , $2 , etc.
首頁 web前端 js教程 實用的JS綜述,用於掌握正則表達(dá)式(REGEX)

實用的JS綜述,用於掌握正則表達(dá)式(REGEX)

Jun 28, 2025 am 01:24 AM

正則表達(dá)式在JavaScript中是一種強大的模式匹配工具,通過使用/pattern/語法定義匹配規(guī)則,並可結(jié)合.test()或.match()方法進(jìn)行驗證或提取信息。例如,/hello/用於匹配字符串中的“hello”,而添加i標(biāo)誌如/hello/i則實現(xiàn)不區(qū)分大小寫的匹配。特殊字符如.、*、 等需用反斜杠轉(zhuǎn)義以匹配字面值,同時可使用\d(數(shù)字)、\w(單詞字符)、\s(空白)等快捷符號。標(biāo)誌符g(全局搜索)、i(忽略大小寫)、m(多行模式)可增強匹配靈活性。通過括號()可分組並捕獲匹配內(nèi)容,如從電子郵件中提取用戶名和域名,且替換操作可通過$1、$2等引用捕獲組實現(xiàn)動態(tài)替換,如將日期格式Y(jié)YYY-MM-DD轉(zhuǎn)換為MM/DD/YYYY。使用時應(yīng)仔細(xì)測試以確保準(zhǔn)確性。

A practical JS roundup for mastering regular expressions (RegEx)

If you're trying to get a solid grip on regular expressions in JavaScript, you're not alone. RegEx can feel like black magic at first — cryptic symbols that somehow match complex patterns. But once you understand how the pieces fit together, it becomes one of the most powerful tools in your JS toolkit. This isn't about memorizing every flag or escape sequence; it's about knowing how to apply them when you need to.

A practical JS roundup for mastering regular expressions (RegEx)

Matching basic patterns with /pattern/

At its core, a regular expression is just a pattern wrapped in slashes: /hello/ will look for the exact word "hello" in a string. This is case-sensitive by default, so "Hello" won't match unless you add the i flag: /hello/i .

A practical JS roundup for mastering regular expressions (RegEx)

You'll often use this inside .test() or .match() methods:

 /hello/.test("hello world"); // true
"hello world".match(/hello/); // ["hello"]

Some characters have special meaning — like . , * , , ? , $ , and ^ . If you want to match them literally, you need to escape them with a backslash: /\.com$/ checks if a string ends with ".com".

A practical JS roundup for mastering regular expressions (RegEx)

A few common shortcuts:

  • \d matches any digit
  • \w matches word characters (letters, digits, underscores)
  • \s matches whitespace

And their opposites:

  • \D = non-digit
  • \W = non-word character
  • \S = non-whitespace

Using flags for more flexibility

Flags modify how your regex behaves. The most commonly used ones are:

  • g (global): keeps searching after the first match
  • i (case-insensitive): ignores uppercase/lowercase differences
  • m (multiline): changes how ^ and $ behave (more on that later)

For example, without g , .match() returns only the first match. With it, you get all:

 "a1b2c3".match(/\d/); // ["1"]
"a1b2c3".match(/\d/g); // ["1", "2", "3"]

The i flag helps when user input might vary in case:

 /youtube/i.test("YouTube"); // true

Multiline mode ( m ) is useful when working with line-based content like logs or code blocks. Normally, ^ and $ match the start and end of the entire string. In multiline mode, they match the start/end of each line.


Capturing and grouping with parentheses

Parentheses () let you group parts of a pattern and capture what they match. This comes in handy when extracting specific parts of a string.

Take an example where we want to extract the username and domain from an email:

 const str = "user@example.com";
const match = str.match(/^(\w )@([\w\.] )$/);

console.log(match[1]); // "user"
console.log(match[2]); // "example.com"

Here, the parentheses define two groups:

  1. One before the @
  2. One after

Note that match returns an array where index 0 is the full match, and subsequent indexes correspond to captured groups.

If you don't need to capture, but still want to group (eg, for repeating a pattern), use (?:...) instead:

 /(abc) / // captures "abc" as a group
/(?:abc) / // matches "abcabc", but doesn't store the group

Replacing text dynamically with $1 , $2 , etc.

One of the most practical uses of regex is replacing parts of strings. You can do static replacements easily with .replace() , but combining it with regex lets you do dynamic swaps using captured groups.

Let's say you want to convert date formats from YYYY-MM-DD to MM/DD/YYYY :

 const dateStr = "2024-05-15";
const newDate = dateStr.replace(/^(\d{4})-(\d{2})-(\d{2})$/, "$2/$3/$1");
// Result: "05/15/2024"

In the replacement string:

  • $1 refers to the first captured group (year)
  • $2 refers to the second (month)
  • $3 refers to the third (day)

This works even with multiple matches if you use the global flag:

 "img1.jpg img2.png".replace(/(\w )\.(jpg|png)/g, "thumb_$1.$2");
// Result: "thumb_img1.jpg thumb_img2.png"

Just remember: always test your regex carefully, especially when dealing with user-generated data. A small mistake can lead to unexpected matches or missed cases.

基本上就這些。

以上是實用的JS綜述,用於掌握正則表達(dá)式(REGEX)的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
如何在node.js中提出HTTP請求? 如何在node.js中提出HTTP請求? Jul 13, 2025 am 02:18 AM

在Node.js中發(fā)起HTTP請求有三種常用方式:使用內(nèi)置模塊、axios和node-fetch。 1.使用內(nèi)置的http/https模塊無需依賴,適合基礎(chǔ)場景,但需手動處理數(shù)據(jù)拼接和錯誤監(jiān)聽,例如用https.get()獲取數(shù)據(jù)或通過.write()發(fā)送POST請求;2.axios是基於Promise的第三方庫,語法簡潔且功能強大,支持async/await、自動JSON轉(zhuǎn)換、攔截器等,推薦用於簡化異步請求操作;3.node-fetch提供類似瀏覽器fetch的風(fēng)格,基於Promise且語法簡單

JavaScript數(shù)據(jù)類型:原始與參考 JavaScript數(shù)據(jù)類型:原始與參考 Jul 13, 2025 am 02:43 AM

JavaScript的數(shù)據(jù)類型分為原始類型和引用類型。原始類型包括string、number、boolean、null、undefined和symbol,其值不可變且賦值時復(fù)制副本,因此互不影響;引用類型如對象、數(shù)組和函數(shù)存儲的是內(nèi)存地址,指向同一對象的變量會相互影響。判斷類型可用typeof和instanceof,但需注意typeofnull的歷史問題。理解這兩類差異有助於編寫更穩(wěn)定可靠的代碼。

React與Angular vs Vue:哪個JS框架最好? React與Angular vs Vue:哪個JS框架最好? Jul 05, 2025 am 02:24 AM

選哪個JavaScript框架最好?答案是根據(jù)需求選擇最適合的。 1.React靈活自由,適合需要高度定制、團(tuán)隊有架構(gòu)能力的中大型項目;2.Angular提供完整解決方案,適合企業(yè)級應(yīng)用和長期維護(hù)的大項目;3.Vue上手簡單,適合中小型項目或快速開發(fā)。此外,是否已有技術(shù)棧、團(tuán)隊規(guī)模、項目生命週期及是否需要SSR也都是選擇框架的重要因素??傊?,沒有絕對最好的框架,適合自己需求的就是最佳選擇。

JavaScript時間對象,某人構(gòu)建了一個eactexe,在Google Chrome上更快的網(wǎng)站等等 JavaScript時間對象,某人構(gòu)建了一個eactexe,在Google Chrome上更快的網(wǎng)站等等 Jul 08, 2025 pm 02:27 PM

JavaScript開發(fā)者們,大家好!歡迎閱讀本週的JavaScript新聞!本週我們將重點關(guān)注:Oracle與Deno的商標(biāo)糾紛、新的JavaScript時間對象獲得瀏覽器支持、GoogleChrome的更新以及一些強大的開發(fā)者工具。讓我們開始吧! Oracle與Deno的商標(biāo)之爭Oracle試圖註冊“JavaScript”商標(biāo)的舉動引發(fā)爭議。 Node.js和Deno的創(chuàng)建者RyanDahl已提交請願書,要求取消該商標(biāo),他認(rèn)為JavaScript是一個開放標(biāo)準(zhǔn),不應(yīng)由Oracle

什麼是緩存API?如何與服務(wù)人員使用? 什麼是緩存API?如何與服務(wù)人員使用? Jul 08, 2025 am 02:43 AM

CacheAPI是瀏覽器提供的一種緩存網(wǎng)絡(luò)請求的工具,常與ServiceWorker配合使用,以提升網(wǎng)站性能和離線體驗。 1.它允許開發(fā)者手動存儲如腳本、樣式表、圖片等資源;2.可根據(jù)請求匹配緩存響應(yīng);3.支持刪除特定緩存或清空整個緩存;4.通過ServiceWorker監(jiān)聽fetch事件實現(xiàn)緩存優(yōu)先或網(wǎng)絡(luò)優(yōu)先等策略;5.常用於離線支持、加快重複訪問速度、預(yù)加載關(guān)鍵資源及後臺更新內(nèi)容;6.使用時需注意緩存版本控制、存儲限制及與HTTP緩存機(jī)制的區(qū)別。

處理諾言:鏈接,錯誤處理和承諾在JavaScript中 處理諾言:鏈接,錯誤處理和承諾在JavaScript中 Jul 08, 2025 am 02:40 AM

Promise是JavaScript中處理異步操作的核心機(jī)制,理解鍊式調(diào)用、錯誤處理和組合器是掌握其應(yīng)用的關(guān)鍵。 1.鍊式調(diào)用通過.then()返回新Promise實現(xiàn)異步流程串聯(lián),每個.then()接收上一步結(jié)果並可返回值或Promise;2.錯誤處理應(yīng)統(tǒng)一使用.catch()捕獲異常,避免靜默失敗,並可在catch中返回默認(rèn)值繼續(xù)流程;3.組合器如Promise.all()(全成功才成功)、Promise.race()(首個完成即返回)和Promise.allSettled()(等待所有完成)

利用Array.Prototype方法用於JavaScript中的數(shù)據(jù)操作 利用Array.Prototype方法用於JavaScript中的數(shù)據(jù)操作 Jul 06, 2025 am 02:36 AM

JavaScript數(shù)組內(nèi)置方法如.map()、.filter()和.reduce()可簡化數(shù)據(jù)處理;1).map()用於一對一轉(zhuǎn)換元素生成新數(shù)組;2).filter()按條件篩選元素;3).reduce()用於聚合數(shù)據(jù)為單一值;使用時應(yīng)避免誤用導(dǎo)致副作用或性能問題。

JS綜述:深入研究JavaScript事件循環(huán) JS綜述:深入研究JavaScript事件循環(huán) Jul 08, 2025 am 02:24 AM

JavaScript的事件循環(huán)通過協(xié)調(diào)調(diào)用棧、WebAPI和任務(wù)隊列來管理異步操作。 1.調(diào)用棧執(zhí)行同步代碼,遇到異步任務(wù)時交由WebAPI處理;2.WebAPI在後臺完成任務(wù)後將回調(diào)放入相應(yīng)的隊列(宏任務(wù)或微任務(wù));3.事件循環(huán)檢查調(diào)用棧是否為空,若為空則從隊列中取出回調(diào)推入調(diào)用棧執(zhí)行;4.微任務(wù)(如Promise.then)優(yōu)先於宏任務(wù)(如setTimeout)執(zhí)行;5.理解事件循環(huán)有助於避免阻塞主線程並優(yōu)化代碼執(zhí)行順序。

See all articles