最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how to replace url in css using regexp (javascript) - Stack Overflow

programmeradmin3浏览0评论
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');}";

result

#anything {
    behavior:url("#");
}

#anything {
    background:transparent url('#') no-repeat;
}

#anything {
    background-image:url('#');
}

How can i do that ?

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');}";

result

#anything {
    behavior:url("#");
}

#anything {
    background:transparent url('#') no-repeat;
}

#anything {
    background-image:url('#');
}

How can i do that ?

Share Improve this question asked Aug 29, 2010 at 19:51 faressoftfaressoft 19.7k44 gold badges107 silver badges149 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

Replace # below with $2 if you want to get the URL with single quotes.

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('#')");

For others who e here looking for a general solution that preserves both whitespace and quotes:

//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);

outputs

one url(*two*) url('*three*') url("*four*")  url  (  *five*  ) 

Example: http://jsfiddle/GcsLQ/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("#")');

If you want the space formatting as well, do this:

Example: http://jsfiddle/GcsLQ/3/

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');

EDIT: Added quotes to the replaced URL.

发布评论

评论列表(0)

  1. 暂无评论