JavaScript 提取
在 JavaScript 中,我们经常需要从字符串中提取特定的信息或者子串。这个过程称为提取。在本文中,我们将详细介绍如何在 JavaScript 中进行提取操作,包括提取子串、提取数字、提取特定格式的信息等。
提取子串
1. 使用 substring
方法提取子串
substring
方法可以从一个字符串中提取指定位置的子串。它接受两个参数,分别是起始位置和结束位置(不包括结束位置)。
const str = "Welcome to geek-docs.com";
const subStr = str.substring(11, 20);
console.log(subStr); // 输出: geek-docs
Output:
2. 使用 slice
方法提取子串
slice
方法也可以用来提取子串,它与 substring
方法类似,但是可以接受负数作为参数,表示从字符串末尾开始计算位置。
const str = "JavaScript is fun at geek-docs.com";
const subStr = str.slice(-14, -4);
console.log(subStr); // 输出: geek-docs
Output:
3. 使用正则表达式提取子串
正则表达式在 JavaScript 中也可以用来提取子串。下面是一个示例,提取字符串中的数字部分。
const str = "The price is $50 at geek-docs.com";
const num = str.match(/\d+/)[0];
console.log(num); // 输出: 50
Output:
提取数字
4. 使用 parseInt
提取整数
parseInt
函数可以将字符串转换为整数,如果字符串中包含非数字字符,则会截断并返回有效的数字部分。
const str = "123abc456";
const num = parseInt(str);
console.log(num); // 输出: 123
Output:
5. 使用正则表达式提取数字
正则表达式也可以用来提取字符串中的数字部分。
const str = "The price is $50 at geek-docs.com";
const num = parseInt(str.match(/\d+/)[0]);
console.log(num); // 输出: 50
Output:
提取特定格式的信息
6. 提取邮箱地址
下面是一个示例代码,提取字符串中的邮箱地址。
const str = "Contact us at info@geek-docs.com for more information";
const email = str.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/)[0];
console.log(email); // 输出: info@geek-docs.com
Output:
7. 提取 URL
下面是一个示例代码,提取字符串中的 URL。
const str = "Visit our website at https://geek-docs.com for more tutorials";
const url = str.match(/(https?|ftp):\/\/[^\s/$.?#].[^\s]*/)[0];
console.log(url); // 输出: https://geek-docs.com
Output:
提取特定位置的信息
8. 提取文件名
下面是一个示例代码,提取 URL 中的文件名部分。
const url = "https://geek-docs.com/javascript-tutorial";
const fileName = url.substring(url.lastIndexOf("/") + 1);
console.log(fileName); // 输出: javascript-tutorial
Output:
9. 提取域名
下面是一个示例代码,提取 URL 中的域名部分。
const url = "https://geek-docs.com/javascript-tutorial";
const domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/)[1];
console.log(domain); // 输出: geek-docs.com
Output:
提取特定格式的信息
10. 提取日期
下面是一个示例代码,提取字符串中的日期信息。
const str = "Today's date is 2022-01-01 at geek-docs.com";
const date = str.match(/\d{4}-\d{2}-\d{2}/)[0];
console.log(date); // 输出: 2022-01-01
Output:
11. 提取电话号码
下面是一个示例代码,提取字符串中的电话号码。
const str = "Contact us at 123-456-7890 for assistance";
const phone = str.match(/\d{3}-\d{3}-\d{4}/)[0];
console.log(phone); // 输出: 123-456-7890
Output: