網(wǎng)站域名查詢官網(wǎng)網(wǎng)絡(luò)平臺(tái)
title: WebAPI語(yǔ)法 date: 2025-01-28 12:00:00 tags:- 前端 categories:- 前端
WEB API
了解DOM的結(jié)構(gòu)并掌握其基本的操作,體驗(yàn) DOM 在開(kāi)發(fā)中的作用
API簡(jiǎn)介
就是使用js來(lái)操作html和瀏覽器
什么是DOM?
就是一個(gè)文檔對(duì)象模型,是用來(lái)呈現(xiàn)預(yù)計(jì)于任意html交互的API.
一句話:是瀏覽器提供的一套專門來(lái)操作網(wǎng)頁(yè)內(nèi)容的功能。
-
DOM :開(kāi)發(fā)網(wǎng)頁(yè)內(nèi)容特效和實(shí)現(xiàn)用戶交互。
-
DOM樹(shù)
將html文檔以樹(shù)狀結(jié)構(gòu)直觀的呈現(xiàn)出來(lái),我們稱之為文檔樹(shù),DOm樹(shù)
描述網(wǎng)頁(yè)內(nèi)容關(guān)系的名詞。
作用:文檔樹(shù)直觀的體現(xiàn)了標(biāo)簽與標(biāo)簽的關(guān)系
DOM對(duì)象(重要)
-
對(duì)象:瀏覽器根據(jù)html標(biāo)簽生成的Js對(duì)象
-
所有的標(biāo)簽屬性都可以在這個(gè)對(duì)象上面找到
-
修改這個(gè)對(duì)象的屬性會(huì)自動(dòng)映射到標(biāo)簽身上。
核心思想:把網(wǎng)頁(yè)內(nèi)容當(dāng)作對(duì)象來(lái)處理。
Document :是DOM里面提供的一個(gè)對(duì)象
-
所以他提供的屬性和方法都是用來(lái)訪問(wèn)和操作網(wǎng)頁(yè)內(nèi)容的
-
網(wǎng)頁(yè)內(nèi)容都在document里面
獲取一個(gè)DOM 元素我們使用誰(shuí)?能直接操作修改嗎?
一般我們用的誰(shuí)querySelector() 可以直接操作修改
獲取多個(gè)DOM 元素我們使用querySelctorAll(),不可以直接進(jìn)行修改,只能通過(guò)遍歷的方式一次給里面的元素做修改。
根據(jù)CSS選擇器來(lái)獲取DOM元素(重點(diǎn))
document.querySelctorAll('css選擇器')
得到的是一個(gè)偽數(shù)組
-
有長(zhǎng)度有索引號(hào)的數(shù)組
-
但是沒(méi)有pop(),push()等數(shù)組的方法
想要得到里面的每一個(gè)對(duì)象,則需要遍歷(for)來(lái)實(shí)現(xiàn)。
那么我應(yīng)該怎么做呢?
//獲取元素 const lis = document,querySelectorAll('.nav li') //console.log(lis) for(let i = 0;i<lis.length;i++) {console.log(lis[i]); //每一個(gè)小li對(duì)象 }
小括號(hào)里面的參數(shù)必須是字符串,也就是必須加引號(hào)。
其他獲取DOM元素的方法
document.getElementById('nav') //根據(jù)id獲取一個(gè)元素
操作元素內(nèi)容
目標(biāo):能夠修改元素的文本更換內(nèi)容
DOM對(duì)象就是根據(jù)標(biāo)簽生成的,所以操作標(biāo)簽,本質(zhì)上就是操作DOM對(duì)象
就是操作對(duì)象使用的點(diǎn)語(yǔ)法
如果想要修改標(biāo)簽元素的里面的內(nèi)容,那么可以使用如下的幾種方式
-
對(duì)象.innerText屬性
那么具體上是怎么要的呢
<div class="box">我是文字的內(nèi)容</div> <script> //獲取元素 const box = document.querySelector('.box') //修改文字內(nèi)容。對(duì)象.innerText 屬性 console.log(box.innerText) //獲取文字內(nèi)容 box.innerText = '我是一個(gè)盒子' </script>
innerText 屬性 顯示純文本,不解析標(biāo)簽
可以將文本內(nèi)容添加/更新到任意標(biāo)簽位置
-
對(duì)象.innerHTML屬性
<div class="box">我是文字的內(nèi)容</div> <script> //獲取元素 const box = document.querySelector('.box') //修改文字內(nèi)容。對(duì)象.innerText 屬性 console.log(box.innerText) //獲取文字內(nèi)容 box.innerHTML = '<strong>我要更換</strong>' </script>
一個(gè)具體例子
<script> //線聲明一下數(shù)組 const personArr = ['周杰倫','sw','qd','wdw'] //隨機(jī)數(shù)數(shù)組下標(biāo) const random = Math.floor(Math.random() * personArr.length) //獲取one 元素 const one = doucument.querySelctor('#one') </script>
操作元素屬性
對(duì)象.屬性 = 值
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head> <body><img src="./images/1.webp" alt=""><script>// 1. 獲取圖片元素const img = document.querySelector('img');// 2. 修改圖片對(duì)象的屬性img.src = './images/2.webp';img.title = 'pink老師的藝術(shù)照';</script> </body> </html>
然后再寫(xiě)一個(gè)生成隨機(jī)照片的程序
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>隨機(jī)圖片</title> </head> <body><img src="./images/1.webp" alt=""><script>// 獲取 N ~ M 的隨機(jī)整數(shù)function getRandom(N, M) {return Math.floor(Math.random() * (M - N + 1)) + N;} ?// 1. 獲取圖片對(duì)象const img = document.querySelector('img'); ?// 2. 隨機(jī)得到序號(hào)const random = getRandom(1, 6); ?// 3. 更換路徑img.src = `./images/${random}.webp`;</script> </body> </html>
這個(gè)得記住,當(dāng)模版來(lái)記憶
操作對(duì)象的樣式屬性
img.src = ./images/${random}.webp
; 這里是重點(diǎn),也是精髓所在
小駝峰命名法(Camel Case)是一種命名約定,通常用于編程中變量、函數(shù)、對(duì)象等的命名。
特點(diǎn):
1. 首字母小寫(xiě):小駝峰命名法的第一個(gè)單詞以小寫(xiě)字母開(kāi)頭。
2. 后續(xù)單詞首字母大寫(xiě):從第二個(gè)單詞開(kāi)始,每個(gè)單詞的首字母大寫(xiě),其余字母小寫(xiě)。
3. **不使用分隔符**:單詞之間不使用下劃線、連字符等,僅通過(guò)字母大小寫(xiě)區(qū)分單詞邊界。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>修改樣式</title> </head> <body><div class="box"></div><script>// 1. 獲取元素const box = document.querySelector('.box'); ?// 2. 修改樣式屬性 對(duì)象.style.樣式屬性 = '值' 別忘了跟單位box.style.width = '300px';box.style.backgroundColor = 'hotpink';box.style.border = '2px solid blue';box.style.borderTop = '2px solid red';</script> </body> </html>
注意這個(gè)格式
小駝峰形式
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>通過(guò)類名修改樣式</title><style>.box {width: 300px;height: 200px;background-color: hotpink;border: 1px solid #000;}</style> </head> <body><div></div><script>// 1. 獲取元素const div = document.querySelector('div');// 2. 添加類名 class 是個(gè)關(guān)鍵字 我們用 classNamediv.className = 'box';</script> </body> </html>
如果你想更換的是nav 的話,可以在添加類名也就是第2步鞋
Div.className = 'nav box'
操作元素樣式屬性
-
通過(guò)classList 操作類控制CSS
-
為了解決className 容易覆蓋以前的類名,我們可以通過(guò)classList 方式追加和刪除類名
通過(guò)classList修改樣式
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>classList.add 示例</title><style>.box {width: 100px;height: 100px;background-color: lightgray;}.active {background-color: lightblue;border: 2px solid blue;}</style> </head> <body><div class="box">文字</div><script>//獲取元素const box = document.querySelector('.box')// 添加類名 activebox.classList.add('active')//刪除一個(gè)類box.claaList.remove('active')//切換一個(gè)類box.classList.togglē('active')</script> </body> </html>
輪播圖
首先隨機(jī)數(shù)
隨機(jī)數(shù)(記住)
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>隨機(jī)內(nèi)容更新</title><style>.slider-wrapper img {width: 300px;height: 200px;}.slider-footer {padding: 10px;text-align: center;}</style> </head> <body><div class="slider-wrapper"><img src="placeholder.jpg" alt="隨機(jī)圖片" /></div><div class="slider-footer"><p>占位文字</p></div> ?<script>const sliderData = [{ url: 'image1.jpg', title: '圖片一標(biāo)題', color: '#ffcccc' },{ url: 'image2.jpg', title: '圖片二標(biāo)題', color: '#ccffcc' },{ url: 'image3.jpg', title: '圖片三標(biāo)題', color: '#ccccff' }] ?const random = parseInt(Math.random() * sliderData.length) ?const img = document.querySelector('.slider-wrapper img')img.src = sliderData[random].url ?const p = document.querySelector('.slider-footer p')p.innerHTML = sliderData[random].title ?const footer = document.querySelector('.slider-footer')footer.style.backgroundColor = sliderData[random].color</script> </body> </html>
加小點(diǎn)
的具體實(shí)現(xiàn)
<div class="slider-wrapper"><img src="placeholder.jpg" alt="圖片"><ul class="slider-indicator"><li></li><li></li><li></li></ul> </div>
.slider-wrapper {position: relative;width: 300px;height: 200px; } ? .slider-wrapper img {width: 100%;height: 100%; } ? .slider-indicator {position: absolute;bottom: 10px;left: 50%;transform: translateX(-50%);display: flex;justify-content: center;list-style: none;padding: 0; } ? .slider-indicator li {width: 10px;height: 10px;background-color: lightgray;border-radius: 50%;margin: 0 5px;cursor: pointer; } ? .slider-indicator li.active {background-color: blue; /* 當(dāng)前選中小圓點(diǎn)的顏色 */ }
const sliderData = [{ url: 'image1.jpg', title: '圖片一標(biāo)題', color: '#ffcccc' },{ url: 'image2.jpg', title: '圖片二標(biāo)題', color: '#ccffcc' },{ url: 'image3.jpg', title: '圖片三標(biāo)題', color: '#ccccff' } ]; ? // 隨機(jī)選擇一個(gè)圖片和對(duì)應(yīng)的小圓點(diǎn) const random = parseInt(Math.random() * sliderData.length); ? // 更新圖片 const img = document.querySelector('.slider-wrapper img'); img.src = sliderData[random].url; ? // 更新標(biāo)題 const p = document.querySelector('.slider-footer p'); p.innerHTML = sliderData[random].title; ? // 更新背景顏色 const footer = document.querySelector('.slider-footer'); footer.style.backgroundColor = sliderData[random].color; ? // 選中小圓點(diǎn)并添加 active 類 const li = document.querySelector(`.slider-indicator li:nth-child(${random + 1})`); li.classList.add('active');
操作表單元素屬性
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>表單值操作</title> </head> <body><input type="text" value="電腦" id="uname"> ?<script>// 1. 獲取元素const uname = document.querySelector('input'); ?// 2. 獲取值// 獲取表單里當(dāng)前的值,用 uname.valueconsole.log(uname.value); // 輸出:電腦 ?// innerHTML 無(wú)法獲取表單值console.log(uname.innerHTML); // 輸出:undefined 或空字符串 ?// 3. 設(shè)置表單的值uname.value = '我要買電腦';console.log(uname.value); // 輸出:我要買電腦 ?// 4. 獲取和設(shè)置表單類型console.log(uname.type); // 輸出:textuname.type = 'password'; // 將表單類型改為密碼輸入框</script> </body> </html>
操作表屬性(實(shí)現(xiàn)勾選)
自定義屬性
這樣就會(huì)出現(xiàn)5個(gè)<div>
自定義屬性。在html5中推出來(lái)了專門的data-自定義屬性
在標(biāo)簽上一律是以data-開(kāi)頭
在DOM對(duì)象上一律是以dataset對(duì)象方式獲取
<div data-id="1" data-spm="不知道">1</div> <div data-id="2">2</div> <div data-id="3">3</div> <div data-id="4">4</div> <div data-id="5">5</div> const one = document.querySelector('div'); console.log(one.dataset.id); // 輸出:1 console.log(one.dataset.spm); // 輸出:不知道
定時(shí)器
間歇函數(shù)
<body><script>第一種方法setInterval(fuction(){console.log('1111')},1000)第二種方法setInterval(fn,3000)關(guān)閉定時(shí)器fuction fn(){console.log('1111')}let n = setInterval(fn,1000)console.log(n)clearInterval(n)</script> </body>
實(shí)現(xiàn)用戶倒計(jì)時(shí)效果
let i = 1 setInterval(fuction (){ i++ document.write(i) },200)
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>倒計(jì)時(shí)啟用按鈕</title><style>.btn {padding: 10px 20px;font-size: 16px;cursor: not-allowed;}.btn:enabled {cursor: pointer;}</style> </head> <body><button class="btn" disabled>我已經(jīng)閱讀用戶協(xié)議(5)</button> ?<script>// 1. 獲取元素const btn = document.querySelector('.btn');// console.log(btn.innerHTML); // 按鈕的初始內(nèi)容 ?// 2. 倒計(jì)時(shí)let i = 5; // 倒計(jì)時(shí)初始值// 2.1 開(kāi)啟定時(shí)器let n = setInterval(function () {i--; // 倒計(jì)時(shí)減少// 更新按鈕文字btn.innerHTML = `我已經(jīng)閱讀用戶協(xié)議(${i})`;// 判斷倒計(jì)時(shí)是否結(jié)束if (i === 0) {clearInterval(n); // 關(guān)閉定時(shí)器// 定時(shí)器停止后,按鈕可用,文字更新為“同意”btn.disabled = false;btn.innerHTML = '同意';}}, 1000); // 每秒執(zhí)行一次</script> </body> </html>
輪播圖定時(shí)器版本
論比
事件監(jiān)聽(tīng)
程序檢測(cè)是否有事件發(fā)生。
關(guān)閉廣告
日期對(duì)象
const date = new
const date = new Date() console.log(data) console.log(date.getFullYear()); const date1 = new Date('') console.log(date1) ?
時(shí)間戳
在 JavaScript 中,時(shí)間戳(Timestamp) 是指從 1970 年 1 月 1 日 00:00:00 UTC 開(kāi)始的毫秒數(shù),用于表示一個(gè)具體的時(shí)間點(diǎn)。以下是關(guān)于時(shí)間戳的相關(guān)知識(shí)和常用方法。
這是獲得時(shí)間的三種方式
查找DOM節(jié)點(diǎn)
在前端開(kāi)發(fā)中,DOM(Document Object Model)節(jié)點(diǎn)是 HTML 文檔的基礎(chǔ)組成部分。DOM 是一種用于表示和操作 HTML 和 XML 文檔的編程接口。
什么是 DOM 節(jié)點(diǎn)?
? 節(jié)點(diǎn)(Node) 是 DOM 樹(shù)中的基本單元。
? 每個(gè)節(jié)點(diǎn)代表 HTML 文檔中的一部分,比如標(biāo)簽、屬性、文本等。
? 整個(gè) HTML 文檔被解析后,會(huì)被表示為一個(gè)由節(jié)點(diǎn)組成的樹(shù)狀結(jié)構(gòu),稱為 DOM 樹(shù)。元素節(jié)點(diǎn) 表示 HTML 標(biāo)簽,比如
查找節(jié)點(diǎn)
通過(guò) ID 查找
const node = document.getElementById("myID");
通過(guò)類名查找:
const nodes = document.getElementsByClassName("myClass");
通過(guò)標(biāo)簽名查找:
const nodes = document.getElementsByTagName("div");
使用 querySelector:
const node = document.querySelector(".myClass"); // 選擇第一個(gè)符合條件的節(jié)點(diǎn) const nodes = document.querySelectorAll(".myClass"); // 選擇所有符合條件的節(jié)點(diǎn)
父子節(jié)點(diǎn)
增加節(jié)點(diǎn)
創(chuàng)造節(jié)點(diǎn)
const newDiv = document.createElement("div");
添加子節(jié)點(diǎn):
const parent = document.getElementById("parent"); const child = document.createElement("div"); parent.appendChild(child);
在指定位置插入節(jié)點(diǎn)
const parent = document.getElementById("parent"); const newNode = document.createElement("p"); const referenceNode = document.getElementById("child"); parent.insertBefore(newNode, referenceNode);
刪除節(jié)點(diǎn):
const parent = document.getElementById("parent"); const child = document.getElementById("child"); parent.removeChild(child);
修改節(jié)點(diǎn)內(nèi)容
const node = document.getElementById("myID"); node.textContent = "New Content";
修改節(jié)點(diǎn)屬性
const node = document.getElementById("myID"); node.setAttribute("class", "newClass");
DOM 節(jié)點(diǎn)關(guān)系
在 DOM 樹(shù)中,節(jié)點(diǎn)之間存在層級(jí)關(guān)系:
? 父節(jié)點(diǎn)(Parent Node): 使用 parentNode 屬性訪問(wèn)。
const parent = childNode.parentNode;
? 子節(jié)點(diǎn)(Child Nodes): 使用 childNodes 屬性訪問(wèn)(包括文本節(jié)點(diǎn))。
const children = parentNode.childNodes;
? 第一個(gè)子節(jié)點(diǎn)/最后一個(gè)子節(jié)點(diǎn):
const firstChild = parentNode.firstChild; const lastChild = parentNode.lastChild;
? 兄弟節(jié)點(diǎn)(Sibling Nodes):
const nextSibling = currentNode.nextSibling; // 下一個(gè)節(jié)點(diǎn) const previousSibling = currentNode.previousSibling; // 上一個(gè)節(jié)點(diǎn)
M端事件
swipper插件
在swipper插件這里
BOM
在前端開(kāi)發(fā)中,BOM(Browser Object Model,瀏覽器對(duì)象模型)是一個(gè)用于操作瀏覽器窗口和瀏覽器相關(guān)功能的接口。BOM 提供了 JavaScript 與瀏覽器交互的能力,比如控制窗口、導(dǎo)航、獲取瀏覽器信息等。
在前端開(kāi)發(fā)中,BOM(Browser Object Model,瀏覽器對(duì)象模型)是一個(gè)用于操作瀏覽器窗口和瀏覽器相關(guān)功能的接口。BOM 提供了 JavaScript 與瀏覽器交互的能力,比如控制窗口、導(dǎo)航、獲取瀏覽器信息等。
console.log(window.innerWidth); // 瀏覽器窗口的寬度 console.log(window.innerHeight); // 瀏覽器窗口的高度 window.alert("這是一個(gè)彈窗!"); // 顯示警告框 window.open("https://www.example.com"); // 打開(kāi)新窗口
2. navigator 對(duì)象
? 提供瀏覽器和用戶設(shè)備的信息,比如瀏覽器的名稱、版本、操作系統(tǒng)等。
console.log(navigator.userAgent); ? ? // 用戶代理字符串,包含瀏覽器信息 console.log(navigator.platform); ? ? // 操作系統(tǒng)類型 console.log(navigator.language); ? ? // 當(dāng)前使用的語(yǔ)言 console.log(navigator.onLine); ? ? ? // 檢測(cè)是否聯(lián)網(wǎng)
3. location 對(duì)象
? 提供當(dāng)前頁(yè)面的 URL 信息,并可以通過(guò)它操作瀏覽器跳轉(zhuǎn)。
console.log(location.href); ? ? ? ? ? // 當(dāng)前頁(yè)面的完整 URL console.log(location.hostname); ? ? ? // 主機(jī)名 console.log(location.pathname); ? ? ? // 路徑部分 console.log(location.search); ? ? ? ? // 查詢字符串部分 location.assign("https://www.example.com"); // 跳轉(zhuǎn)到指定 URL location.reload(); ? ? ? ? ? ? ? ? ? // 重新加載當(dāng)前頁(yè)面
4. history 對(duì)象
? 提供對(duì)瀏覽器歷史記錄的操作能力。
history.back(); // 返回上一頁(yè) history.forward(); // 前進(jìn)到下一頁(yè) history.go(-2); ? // 跳轉(zhuǎn)到歷史記錄中的指定位置,負(fù)數(shù)表示后退
5. screen 對(duì)象
? 提供與用戶屏幕相關(guān)的信息,比如分辨率。
console.log(screen.width); ? // 屏幕寬度 console.log(screen.height); ? // 屏幕高度 console.log(screen.availWidth); // 可用寬度(減去任務(wù)欄等) console.log(screen.availHeight); // 可用高度
定時(shí)器
JS執(zhí)行機(jī)制
本地存儲(chǔ)
在前端開(kāi)發(fā)中,本地存儲(chǔ)(Local Storage) 是 HTML5 提供的一種持久化存儲(chǔ)方式,用于在瀏覽器中以鍵值對(duì)的形式保存數(shù)據(jù)。這些數(shù)據(jù)保存在用戶的瀏覽器中,即使刷新頁(yè)面或關(guān)閉瀏覽器后數(shù)據(jù)仍然存在。
1. 本地存儲(chǔ)的特點(diǎn)
? 容量大:一般為 5MB,比傳統(tǒng)的 cookie 容量大。
? 持久性:數(shù)據(jù)會(huì)一直保存在瀏覽器中,直到手動(dòng)清除。
? 鍵值對(duì)存儲(chǔ):以字符串形式存儲(chǔ)鍵值對(duì)。
? 僅在同一域名下共享:同一域名下的頁(yè)面可以訪問(wèn)相同的本地存儲(chǔ)。
(1) 保存數(shù)據(jù)
使用 localStorage.setItem(key, value) 方法。
localStorage.setItem('username', 'Alice');
? 參數(shù)說(shuō)明:
? key:鍵名(字符串)。
? value:鍵值(必須是字符串)。
(2) 讀取數(shù)據(jù)
使用 localStorage.getItem(key) 方法。
const username = localStorage.getItem('username'); console.log(username); // 輸出:Alice
(3) 刪除某個(gè)鍵值對(duì)
使用 localStorage.removeItem(key) 方法。
localStorage.removeItem('username');
(4) 清除所有數(shù)據(jù)
使用 localStorage.clear() 方法。
localStorage.clear();
(5) 獲取所有鍵
使用 localStorage.key(index) 方法獲取指定索引的鍵名。
for (let i = 0; i < localStorage.length; i++) {console.log(localStorage.key(i)); // 遍歷所有鍵名 }
只能存儲(chǔ)字符串
存儲(chǔ)復(fù)雜數(shù)據(jù)類型
1. 存儲(chǔ)對(duì)象
存儲(chǔ)方法
將對(duì)象通過(guò) JSON.stringify() 轉(zhuǎn)換為字符串后存儲(chǔ):
const user = { name: 'Alice', age: 25, hobbies: ['reading', 'coding'] }; localStorage.setItem('user', JSON.stringify(user)); // 轉(zhuǎn)為字符串存儲(chǔ)
讀取方法
從本地存儲(chǔ)中獲取字符串后,用 JSON.parse() 轉(zhuǎn)換回對(duì)象:
const userStr = localStorage.getItem('user'); // 獲取字符串 if (userStr) {const user = JSON.parse(userStr); // 轉(zhuǎn)為對(duì)象console.log(user.name); // 輸出:Aliceconsole.log(user.hobbies); // 輸出:['reading', 'coding'] }
Map
map也稱之為映射
join 把數(shù)組轉(zhuǎn)換為字符串
正則表達(dá)式
正則表達(dá)式(Regular Expression)是用來(lái)匹配字符串中字符模式的工具,廣泛應(yīng)用于文本處理,比如驗(yàn)證輸入格式、查找替換字符串、數(shù)據(jù)提取等。
1. 正則表達(dá)式的基礎(chǔ)
正則表達(dá)式由普通字符和元字符(特殊字符)組成,具有靈活且強(qiáng)大的匹配能力。
正則表達(dá)式中的一些特殊字符需要通過(guò)反斜杠 \ 轉(zhuǎn)義才能匹配本身:
? . 匹配 .,* 匹配 *。
? 如果要匹配反斜杠本身,寫(xiě)成 \。
常見(jiàn)正則表達(dá)式作用
-
表單驗(yàn)證
-
過(guò)濾敏感詞
-
字符串中提取我們想要的部分
三組詞語(yǔ)
匹配,替換,提取
const regex = /abc/;
const regex = /hello/i; console.log(regex.test("Hello")); // true
定義-檢測(cè)是否匹配
元字符(Metacharacters) 是正則表達(dá)式中具有特殊含義的字符,用于定義匹配規(guī)則,而不是直接匹配它們的字面值。元字符賦予了正則表達(dá)式強(qiáng)大的功能,使其可以靈活處理字符串模式匹配。
const regex = /a.b/; console.log(regex.test("acb")); // true console.log(regex.test("a_b")); // true console.log(regex.test("ab")); // false
const regex1 = /^hello/; // 必須以 "hello" 開(kāi)頭 console.log(regex1.test("hello world")); // true console.log(regex1.test("world hello")); // false ? const regex2 = /world$/; // 必須以 "world" 結(jié)尾 console.log(regex2.test("hello world")); // true console.log(regex2.test("world hello")); // false
邊界符
const regex1 = /^hello/; // 必須以 "hello" 開(kāi)頭 console.log(regex1.test("hello world")); // true console.log(regex1.test("world hello")); // false ? const regex2 = /world$/; // 必須以 "world" 結(jié)尾 console.log(regex2.test("hello world")); // true console.log(regex2.test("world hello")); // false
(4) {}(量詞)
? {n}:匹配前面的字符恰好 n 次。
? {n,}:匹配前面的字符至少 n 次。
? {n,m}:匹配前面的字符 n 到 m 次。
const regex1 = /a{2}/; // 匹配兩個(gè)連續(xù)的 "a" console.log(regex1.test("aa")); // true console.log(regex1.test("a")); // false ? const regex2 = /a{2,}/; // 匹配至少兩個(gè)連續(xù)的 "a" console.log(regex2.test("aaa")); // true console.log(regex2.test("a")); ? // false ? const regex3 = /a{2,4}/; // 匹配 2 到 4 個(gè)連續(xù)的 "a" console.log(regex3.test("aaa")); // true console.log(regex3.test("aaaaa"));// true(只匹配前 4 個(gè) "a")
const regex1 = /a{2}/; // 匹配兩個(gè)連續(xù)的 "a" console.log(regex1.test("aa")); // true console.log(regex1.test("a")); // false ? const regex2 = /a{2,}/; // 匹配至少兩個(gè)連續(xù)的 "a" console.log(regex2.test("aaa")); // true console.log(regex2.test("a")); ? // false ? const regex3 = /a{2,4}/; // 匹配 2 到 4 個(gè)連續(xù)的 "a" console.log(regex3.test("aaa")); // true console.log(regex3.test("aaaaa"));// true(只匹配前 4 個(gè) "a")
3. 特殊的字符類
正則表達(dá)式還提供了一些預(yù)定義的字符類,可以快速匹配特定類型的字符: