Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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
innerHTML的javascript预匹配_Javascript_Regex - Fatal编程技术网

innerHTML的javascript预匹配

innerHTML的javascript预匹配,javascript,regex,Javascript,Regex,我正在尝试从一个页面中获取 url:“和”, 我尝试过通过谷歌找到的几种不同的解决方案,但最接近的是这个 function pregmatch() { var re = new RegExp("url: '(.*)',", "g"),// the regex txt = 'some text'; // the text on page to be replaced by url newtxt = txt.replace(txt,re); // replace tex

我正在尝试从一个页面中获取

url:“
”,

我尝试过通过谷歌找到的几种不同的解决方案,但最接近的是这个

function pregmatch() {
    var re = new RegExp("url: '(.*)',", "g"),// the regex
       txt = 'some text'; // the text on page to be replaced by url
    newtxt = txt.replace(txt,re); // replace text with found url
    document.body.innerHTML = document.body.innerHTML.replace(txt,newtxt);
}
pregmatch();
但这只是用regex
/url:'(.*),/g
代替
一些文本,而不是所需的url

我还尝试了
newText=txt.replace(txt,re[0])但这是未定义的,我是一个JS新手,因此非常感谢您的帮助

更新:

好的,我想有些小姐明白我在做什么,所以会再试一次

在pages source中有一个部分:

url: 'http://somedomain.com/b3a4f5d2b725a8d',
在页面本身上有一些文本
hello world
,非常适合在页面上添加url,因此我想从源代码中获取url,并用url替换
hello world

ie
var txt='some text'
不是url所在的字符串,实际上只是页面上的文本,将被找到的url替换。

语法为:

string.replace(regex, replacement);
因此:

但是,由于您希望获得url,因此最好使用
.match

url = txt.match(re)[1];
而且您的
re
会更好:

var re = new RegExp("url: '(.*?)',", "g");

这会阻止超出必要的匹配。

您正在用正则表达式替换字符串
txt
中正则表达式的匹配项

正确用法是:

var newtxt = txt.replace(re, "something_to_replace_with");
要获取所有匹配项:

var matches = txt.match(re);

不显式定义正则表达式对象:

var reg = /url: '(.*?)',/;
var txt = "url: 'some text',";
if (reg.test(txt))
   alert(txt.match(reg)[1]);
还要注意

var txt = 'some text';

将不匹配查找单引号的正则表达式,因为上面使用的单引号仅用于将变量定义为字符串——它们实际上不作为字符串本身中的可匹配文本存在。

如果您试图获取链接,为什么要使用替换而不是匹配?当然你只是想知道
url.match(/url:“(.*?”,/)[1]
我确实说过我是一个JS新手,我想实际上我是一个JS新手。
var txt = 'some text';