2010-08-29 10 views
1
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');}"; 

résultatcomment remplacer url dans CSS en utilisant regexp (javascript)

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

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

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

Comment puis-je faire?

Répondre

3

Remplacez # ci-dessous par $2 si vous souhaitez obtenir l'URL avec des guillemets simples.

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\((['"])(.+?)\1\)/g, "url('#')"); 
+0

text = text.replace (/ url \\ ((['"]) (. +?) \ 1 \\)/g," url (' # ') "); Merci, Ce code m'a aidé dans mon projet – faressoft

+0

Votre regex efface la partie 'url()' de sorte que vous êtes juste parti avec ''#''. – user113716

+0

Je suggérerais d'ajouter? après ['"] vous obtenez également des URL sans guillemets ' 'url (http://blabla.com)' .replace (/ url \ ((['"]?) (. +?) \ 1 \)/g, "$ 2"); ' – Largo

0

Exemple:http://jsfiddle.net/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("#")'); 

Si vous voulez que le formatage de l'espace ainsi, faites ceci:

Exemple:http://jsfiddle.net/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: citations Ajouté à l'URL remplacée

0

Pour d'autres qui viennent ici à la recherche d'une solution générale qui préserve les espaces blancs et citations:

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

sorties

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