Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.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
如何使用regexp(javascript)替换css中的url_Javascript_Html_Css_Regex_Url - Fatal编程技术网

如何使用regexp(javascript)替换css中的url

如何使用regexp(javascript)替换css中的url,javascript,html,css,regex,url,Javascript,Html,Css,Regex,Url,结果 var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url text += "#anything {background-image:url('ok.jpg');}"; 我如何才能做到这一点?示例: 如果

结果

var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";
我如何才能做到这一点?

示例:

如果还需要空间格式,请执行以下操作:

例如:

编辑:在被替换的URL中添加引号。

如果您想使用单引号获取URL,请将下面的内容替换为$2

var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";


text = text.replace(/url\([^)]+\)/g, 'url("#")')
    .replace(/{/g,'{\n\t')
    .replace(/}/g,'\n}\n');

对于前来寻求保留空格和引号的通用解决方案的其他人:

输出

//Test data
var css = 'one url(two) url(\'three\') url("four")  url  (  five  )';

css = css.replace(

    // Regex
    /(url\W*\(\W*['"]?\W*)(.*?)(\W*['"]?\W*\))/g,

    // Replacement string
    '$1*$2*$3'

);

console.log(css);

text=text.replace/url\['].+?\1\/g,url;谢谢,这段代码在我的项目中帮助了我。你的正则表达式删除了url部分,所以你只剩下了。我建议添加?在[']之后,也可以得到不带引号的URLurlhttp://blabla.com'.替换/url\[']?.+?\1\/g,$2;
var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += "#anything {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";


text = text.replace(/url\([^)]+\)/g, 'url("#")')
    .replace(/{/g,'{\n\t')
    .replace(/}/g,'\n}\n');
var text = '#anything {behavior:url("csshover.htc");}'; //iam using " with url
text += ".regleft {background:transparent url('img.png') no-repeat;}"; //iam using ' with url
text += "#anything {background-image:url('ok.jpg');}";
text = text.replace(/url\((['"])(.+?)\1\)/g, "url('#')");
//Test data
var css = 'one url(two) url(\'three\') url("four")  url  (  five  )';

css = css.replace(

    // Regex
    /(url\W*\(\W*['"]?\W*)(.*?)(\W*['"]?\W*\))/g,

    // Replacement string
    '$1*$2*$3'

);

console.log(css);
one url(*two*) url('*three*') url("*four*")  url  (  *five*  )