JavaScript 用正则表达式提取查询字符串的过程
查询字符串是跟随问号(?)的URL的一部分,用于向网页或应用传递数据。它通常由用和号(&)分隔的键值对组成。键表示参数,值表示通过参数传递的数据。
本文将讨论如何使用正则表达式从URL中提取查询字符串。
方法:
首先,我们需要定义一个正则表达式模式,该模式将匹配URL的查询字符串。正则表达式是一系列字符,形成一个搜索模式。它可用于检查字符串是否包含指定的搜索模式。
查询字符串的正则表达式模式为:
[?&]([^=]+)(=([^&#]*))?
此模式匹配查询字符串的开头(?),后面跟随由和号(&)分隔的任何键值对。键被捕获在第一个捕获组([^=]+)中,值被捕获在第三个捕获组(([^&#]*))中。
接下来,我们可以使用 JavaScript 中的 RegExp 对象从模式创建正则表达式。我们可以通过将模式传递给 RegExp 构造函数来实现:
const pattern = '[?&]([^=]+)(=([^&#]*))?';
const regex = new RegExp(pattern);
一旦我们有了正则表达式,我们可以使用test()方法来检查URL的查询字符串是否与模式匹配。test()方法返回一个布尔值,指示字符串是否包含匹配项。
示例1: 以下代码使用JavaScript从给定的URL中提取查询字符串,通过将其与正则表达式模式进行匹配,并在匹配时将查询字符串记录到控制台。
C++
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main() {
// URL to be queried
string url = "https://example.com?key1=value1&key2=value2";
// Regular expression pattern
string pattern = "[?&]([^=]+)(=([^&#]*))?";
// Creating a regex object from the pattern
regex regexObj(pattern);
// Creating a match object to hold the matched substring
smatch match;
// Querying the string using the regex
if (regex_search(url, match, regexObj)) {
string queryString = match.str();
cout << queryString << endl;
}
return 0;
}
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args)
{
// url to be queried
final String url
= "https:example.com?key1=value1&key2=value2";
// pattern
final String pattern = "[?&]([^=]+)(=([^&#]*))?";
// building regex from the pattern
Pattern regex = Pattern.compile(pattern);
// querying the string using the regex
Matcher matcher = regex.matcher(url);
if (matcher.find()) {
String queryString = matcher.group();
System.out.println(queryString);
}
}
}
JavaScript
<script>
// url to be queried
const url = 'https://example.com?key1=value1&key2=value2';
// pattern
const pattern = '[?&]([^=]+)(=([^&#]*))?';
// building regex from the pattern
const regex = new RegExp(pattern);
// querying the string using the regex
if (regex.test(url)) {
const queryString = url.match(regex)[0];
console.log(queryString);
}
</script>
C
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
// url to be queried
const string url = "https://example.com?key1=value1&key2=value2";
// pattern
const string pattern = @"[?&]([^=]+)(=([^&#]*))?";
// building regex from the pattern
Regex regex = new Regex(pattern);
// querying the string using the regex
if (regex.IsMatch(url))
{
string queryString = regex.Match(url).Value;
Console.WriteLine(queryString);
}
}
}
Python
import re
# URL to be queried
url = "https://example.com?key1=value1&key2=value2"
# Regular expression pattern
pattern = r"[?&]([^=]+)(=([^&#]*))?".encode('unicode-escape').decode()
# Creating a regex object from the pattern
regex_obj = re.compile(pattern)
# Querying the string using the regex
match = regex_obj.search(url)
if match:
query_string = match.group()
print(query_string)
# This code is contributed by Prajwal Kandekar
输出
?key1=value1
示例2:这段代码使用JavaScript通过正则表达式模式匹配从给定URL中提取查询参数,然后将查询字符串分割为单独的键值对。遍历键值对并将其存储在一个对象中,最后将查询参数对象打印到控制台。
JavaScript
<script>
// Define the URL and the regular expression pattern
const url = 'https://example.com?key1=value1&key2=value2';
const pattern = '[?&]([^=]+)(=([^&#]*))?';
// Create the regular expression object
const regex = new RegExp(pattern);
// Check if the URL matches the pattern
if (regex.test(url)) {
// Extract the query string from the URL
const queryString = url.match(regex)[0];
// Split the query string into individual key-value pairs
const keyValuePairs = queryString.split('&');
// Iterate over the key-value pairs
// store them in an object
const queryParams = {};
keyValuePairs.forEach(pair => {
const [key, value] = pair.split('=');
queryParams[key] = value;
});
// Output the query parameters object
console.log(queryParams);
}
</script>
输出
{ '?key1': 'value1' }
示例3:这段代码使用JavaScript通过正则表达式模式匹配从给定URL中提取查询参数,然后将查询字符串分割为单个的键值对,然后遍历键值对,并将它们存储在一个对象中。最后,遍历query parameters对象,在控制台中输出每个键值对。
JavaScript
<script>
// Define the URL and the regular expression pattern
const url = 'https://example.com?key1=value1&key2=value2';
const pattern = '[?&]([^=]+)(=([^&#]*))?';
// Create the regular expression object
const regex = new RegExp(pattern);
// Check if the URL matches the pattern
if (regex.test(url)) {
// Extract the query string from the URL
const queryString = url.match(regex)[0];
// Split the query string into individual key-value pairs
const keyValuePairs = queryString.split('&');
// Iterate over the key-value pairs
// store them in an object
const queryParams = {};
keyValuePairs.forEach(pair => {
const [key, value] = pair.split('=');
queryParams[key] = value;
});
// Iterate over the query parameters object
// output each key-value pair
for (const [key, value] of Object.entries(queryParams)) {
console.log(`{key}:{value}`);
}
}
</script>
输出
?key1: value1
总之,使用正则表达式从URL中提取查询字符串对于解析和操作通过URL传递的数据是一种有用的技术。通过定义一个正则表达式模式,匹配URL中的查询字符串,并使用RegExp对象和test()方法,可以轻松提取查询字符串,并将其分割为单个键值对。然后,这些键值对可以存储在一个对象中,以便于访问,允许我们轻松地检索和操作通过查询字符串传递的数据。正则表达式是处理字符串的强大工具,这项技术在各种web开发场景中都很有用。