Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript从字符串中提取HTML标记_Javascript_Regex_String_Match - Fatal编程技术网

JavaScript从字符串中提取HTML标记

JavaScript从字符串中提取HTML标记,javascript,regex,string,match,Javascript,Regex,String,Match,我有以下字符串: let html = `<!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <title>Hello, world!</title> </head> <body> <p>Hello, world!</p> </body&

我有以下字符串:

let html = `<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
    <head>
        <title>Hello, world!</title>
    </head>
    <body>
        <p>Hello, world!</p>
    </body>
</html>`;
let html=`
你好,世界!
你好,世界

`;
如何仅提取开始的HTML标记?我只需要:

'<html xmlns="https://www.w3.org/1999/xhtml">'
“”

如果这是最好的方法,请建议使用正则表达式。

如果您想捕获
标记,只需使用
/

这只是搜索

这可以从以下几点看出:

let html=`
你好,世界!
你好,世界

`;
console.log(html.match(//)[0])如果您只想提取第二行,您可以将字符串按\n拆分并获得所需行的值

let html=`
你好,世界!
你好,世界

`; var lines=html.split(/\n/g);
console.log(第[1]行)到目前为止你试过什么吗?我将正则表达式改为//以禁用贪婪匹配。这样,如果字符串为(例如:”),则它可以工作。您还需要使用更快的
]*>
@GTSJoe@revo除了速度还有什么不同?更好的性能来自于
[^>]*
表示贪婪匹配,但
*?
是非贪婪的。前者一次消耗除
以外的所有字符,然后匹配
,但后者一次消耗一个字符,直到达到
。除了
[^>]之外,没有其他区别*
也可以跨越多行。@GTSJoe