如何从此字符串中获取帧名?
<iframe title="recaptcha challenge" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=v1526338122299&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&cb=ylg7rbi4vs61#4u0yaht3nqk" style="width: 100%; height: 100%; outline: 1px solid blue;" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" name="4u0yaht3nqk" frameborder="0"></iframe>
这是我目前的javascript代码:
var str = '<iframe title="recaptcha challenge" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=v1526338122299&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&cb=ylg7rbi4vs61#4u0yaht3nqk" style="width: 100%; height: 100%; outline: 1px solid blue;" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" name="4u0yaht3nqk" frameborder="0"></iframe>';
var res = str.match(/name=/);
console.log(res);
最终输出应如下所示:
4u0yaht3nqk
但我的代码不起作用。有谁能解决这个问题?我需要它只是正则表达式
答案 0 :(得分:0)
您需要使用正则表达式中的括号来捕获name
的值:
var str = '<iframe title="recaptcha challenge" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=v1526338122299&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&cb=ylg7rbi4vs61#4u0yaht3nqk" style="width: 100%; height: 100%; outline: 1px solid blue;" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" name="4u0yaht3nqk" frameborder="0"></iframe>';
var res = str.match(/name="([^"]*)"/)
console.log(res != null ? res[1] : "not found");
请注意,如果name
包含转义引号,则此操作会失败。
答案 1 :(得分:0)
只需添加您想要捕获的内容并使用结果。
var str = '<iframe title="recaptcha challenge" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=v1526338122299&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&cb=ylg7rbi4vs61#4u0yaht3nqk" style="width: 100%; height: 100%; outline: 1px solid blue;" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" name="4u0yaht3nqk" frameborder="0"></iframe>';
var res = str.match(/name="(.+?)"/);//(.+?) contains captured value
console.log(res[1]);
答案 2 :(得分:0)
您可以将字符串转换为正确的DOM节点:
UIStackView
请注意,您必须使用const element = document.createElement("template");
const str = '<iframe title="recaptcha challenge" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=v1526338122299&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&cb=ylg7rbi4vs61#4u0yaht3nqk" style="width: 100%; height: 100%; outline: 1px solid blue;" scrolling="no" sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox" name="4u0yaht3nqk" frameborder="0"></iframe>';
element.innerHTML = str;
const iframe = element.content.firstChild;
return iframe.name;
元素将您的字符串作为template
中的DOM节点进行访问。