如何在JavaScript中用正则表达式提取MsRtcOAuth href的属性值?
Extracting the URL with Regex in JavaScript
Doing the same regex extraction in JavaScript is straightforward—here's how you can replicate your Python logic:
First, define your target string just like you did in Python:
const STRING = 'Bearer trusted_issuers="", client_id="00000004-0000-0ff1-ce00-000000000000", MsRtcOAuth href="https://google.com",grant_type="urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password"';
Next, create your regex pattern. You can use a regex literal (enclosed in / characters) which mirrors your Python regex string:
const regexPattern = /MsRtcOAuth href="(.*?)"/;
Now, to run the search and get the captured group, you have two common, easy-to-use options:
Option 1: Use the exec() method
This works almost exactly like Python's re.search()—it returns a match object (or null if no match is found):
const matchResult = regexPattern.exec(STRING); if (matchResult) { const extractedUrl = matchResult[1]; // Access the first captured group (same as group(1) in Python) console.log(extractedUrl); // Outputs: https://google.com }
Option 2: Use the match() method on the string
You can also call match() directly on your string, which returns an array of matches (or null):
const matchResult = STRING.match(regexPattern); if (matchResult) { const extractedUrl = matchResult[1]; console.log(extractedUrl); // Outputs: https://google.com }
A few quick, important notes:
- The
(.*?)non-greedy match behaves exactly like it does in Python—it stops at the first closing quote instead of matching all the way to the end of the string. - Always check if
matchResultis notnullbefore accessingmatchResult[1]to avoid runtime errors if the pattern doesn't exist in the string. - JavaScript uses 1-based indexing for captured groups, just like Python's
group(1), somatchResult[1]gives you the content inside the first set of parentheses.
内容的提问来源于stack exchange,提问作者Amit Singh
相关产品推荐
相关产品推荐

