2016-01-04 4 views
0

строкового значениязаменить функцию Javascript строки в двойных кавычках

var a="background("text.jpg")"; //this value i got from css 

необходимо заменить двойные кавычки "с || (символ две трубы) в качестве фона (|| text.jpg ||)

a.replace(/"/g, "||") 

Но это не работает, так как я имею строку с уже двойными кавычками в нем background("text.jpg"), можно сделать преобразование.

на самом деле я пытаюсь преобразовать Vw, Vh единица рХ сюда м Lea Verous код исх: https://gist.github.com/LeaVerou/1347501

видеть мой код:

/** 
 
* StyleFix 1.0.3 & PrefixFree 1.0.7 
 
* @author Lea Verou 
 
* MIT license 
 
*/ 
 
(function(){function k(a,b){return[].slice.call((b||document).querySelectorAll(a))}if(window.addEventListener){var e=window.StyleFix={link:function(a){try{if("stylesheet"!==a.rel||a.hasAttribute("data-noprefix"))return}catch(b){return}var c=a.href||a.getAttribute("data-href"),d=c.replace(/[^\/]+$/,""),h=(/^[a-z]{3,10}:/.exec(d)||[""])[0],l=(/^[a-z]{3,10}:\/\/[^\/]+/.exec(d)||[""])[0],g=/^([^?]*)\??/.exec(c)[1],m=a.parentNode,f=new XMLHttpRequest,n;f.onreadystatechange=function(){4===f.readyState&& 
 
n()};n=function(){var b=f.responseText;if(b&&a.parentNode&&(!f.status||400>f.status||600<f.status)){b=e.fix(b,!0,a);if(d)var b=b.replace(/url\(\s*?((?:"|')?)(.+?)\1\s*?\)/gi,function(b,a,c){return/^([a-z]{3,10}:|#)/i.test(c)?b:/^\/\//.test(c)?'url("'+h+c+'")':/^\//.test(c)?'url("'+l+c+'")':/^\?/.test(c)?'url("'+g+c+'")':'url("'+d+c+'")'}),c=d.replace(/([\\\^\$*+[\]?{}.=!:(|)])/g,"\\$1"),b=b.replace(RegExp("\\b(behavior:\\s*?url\\('?\"?)"+c,"gi"),"$1");c=document.createElement("style");c.textContent= 
 
b;c.media=a.media;c.disabled=a.disabled;c.setAttribute("data-href",a.getAttribute("href"));m.insertBefore(c,a);m.removeChild(a);c.media=a.media}};try{f.open("GET",c),f.send(null)}catch(p){"undefined"!=typeof XDomainRequest&&(f=new XDomainRequest,f.onerror=f.onprogress=function(){},f.onload=n,f.open("GET",c),f.send(null))}a.setAttribute("data-inprogress","")},styleElement:function(a){if(!a.hasAttribute("data-noprefix")){var b=a.disabled;a.textContent=e.fix(a.textContent,!0,a);a.disabled=b}},styleAttribute:function(a){var b= 
 
a.getAttribute("style"),b=e.fix(b,!1,a);a.setAttribute("style",b)},process:function(){k('link[rel="stylesheet"]:not([data-inprogress])').forEach(StyleFix.link);k("style").forEach(StyleFix.styleElement);k("[style]").forEach(StyleFix.styleAttribute)},register:function(a,b){(e.fixers=e.fixers||[]).splice(void 0===b?e.fixers.length:b,0,a)},fix:function(a,b,c){for(var d=0;d<e.fixers.length;d++)a=e.fixers[d](a,b,c)||a;return a},camelCase:function(a){return a.replace(/-([a-z])/g,function(b,a){return a.toUpperCase()}).replace("-", 
 
"")},deCamelCase:function(a){return a.replace(/[A-Z]/g,function(b){return"-"+b.toLowerCase()})}};(function(){setTimeout(function(){k('link[rel="stylesheet"]').forEach(StyleFix.link)},10);document.addEventListener("DOMContentLoaded",StyleFix.process,!1)})()}})(); 
 
(function(k){function e(b,c,d,h,l){b=a[b];b.length&&(b=RegExp(c+"("+b.join("|")+")"+d,"gi"),l=l.replace(b,h));return l}if(window.StyleFix&&window.getComputedStyle){var a=window.PrefixFree={prefixCSS:function(b,c,d){var h=a.prefix;-1<a.functions.indexOf("linear-gradient")&&(b=b.replace(/(\s|:|,)(repeating-)?linear-gradient\(\s*(-?\d*\.?\d*)deg/ig,function(b,a,c,d){return a+(c||"")+"linear-gradient("+(90-d)+"deg"}));b=e("functions","(\\s|:|,)","\\s*\\(","$1"+h+"$2(",b);b=e("keywords","(\\s|:)","(\\s|;|\\}|$)", 
 
"$1"+h+"$2$3",b);b=e("properties","(^|\\{|\\s|;)","\\s*:","$1"+h+"$2:",b);if(a.properties.length){var l=RegExp("\\b("+a.properties.join("|")+")(?!:)","gi");b=e("valueProperties","\\b",":(.+?);",function(a){return a.replace(l,h+"$1")},b)}c&&(b=e("selectors","","\\b",a.prefixSelector,b),b=e("atrules","@","\\b","@"+h+"$1",b));b=b.replace(RegExp("-"+h,"g"),"-");return b=b.replace(/-\*-(?=[a-z]+)/gi,a.prefix)},property:function(b){return(0<=a.properties.indexOf(b)?a.prefix:"")+b},value:function(b,c){b= 
 
e("functions","(^|\\s|,)","\\s*\\(","$1"+a.prefix+"$2(",b);b=e("keywords","(^|\\s)","(\\s|$)","$1"+a.prefix+"$2$3",b);0<=a.valueProperties.indexOf(c)&&(b=e("properties","(^|\\s|,)","($|\\s|,)","$1"+a.prefix+"$2$3",b));return b},prefixSelector:function(b){return b.replace(/^:{1,2}/,function(b){return b+a.prefix})},prefixProperty:function(b,c){var d=a.prefix+b;return c?StyleFix.camelCase(d):d}};(function(){var b={},c=[],d=getComputedStyle(document.documentElement,null),h=document.createElement("div").style, 
 
l=function(a){if("-"===a.charAt(0)){c.push(a);a=a.split("-");var d=a[1];for(b[d]=++b[d]||1;3<a.length;)a.pop(),d=a.join("-"),StyleFix.camelCase(d)in h&&-1===c.indexOf(d)&&c.push(d)}};if(0<d.length)for(var g=0;g<d.length;g++)l(d[g]);else for(var e in d)l(StyleFix.deCamelCase(e));var g=0,f,k;for(k in b)d=b[k],g<d&&(f=k,g=d);a.prefix="-"+f+"-";a.Prefix=StyleFix.camelCase(a.prefix);a.properties=[];for(g=0;g<c.length;g++)e=c[g],0===e.indexOf(a.prefix)&&(f=e.slice(a.prefix.length),StyleFix.camelCase(f)in 
 
h||a.properties.push(f));!("Ms"!=a.Prefix||"transform"in h||"MsTransform"in h)&&"msTransform"in h&&a.properties.push("transform","transform-origin");a.properties.sort()})();(function(){function b(a,b){h[b]="";h[b]=a;return!!h[b]}var c={"linear-gradient":{property:"backgroundImage",params:"red, teal"},calc:{property:"width",params:"1px + 5%"},element:{property:"backgroundImage",params:"#foo"},"cross-fade":{property:"backgroundImage",params:"url(a.png), url(b.png), 50%"}};c["repeating-linear-gradient"]= 
 
c["repeating-radial-gradient"]=c["radial-gradient"]=c["linear-gradient"];var d={initial:"color","zoom-in":"cursor","zoom-out":"cursor",box:"display",flexbox:"display","inline-flexbox":"display",flex:"display","inline-flex":"display",grid:"display","inline-grid":"display","max-content":"width","min-content":"width","fit-content":"width","fill-available":"width"};a.functions=[];a.keywords=[];var h=document.createElement("div").style,e;for(e in c){var g=c[e],k=g.property,g=e+"("+g.params+")";!b(g,k)&& 
 
b(a.prefix+g,k)&&a.functions.push(e)}for(var f in d)k=d[f],!b(f,k)&&b(a.prefix+f,k)&&a.keywords.push(f)})();(function(){function b(a){e.textContent=a+"{}";return!!e.sheet.cssRules.length}var c={":read-only":null,":read-write":null,":any-link":null,"::selection":null},d={keyframes:"name",viewport:null,document:'regexp(".")'};a.selectors=[];a.atrules=[];var e=k.appendChild(document.createElement("style")),l;for(l in c){var g=l+(c[l]?"("+c[l]+")":"");!b(g)&&b(a.prefixSelector(g))&&a.selectors.push(l)}for(var m in d)g= 
 
m+" "+(d[m]||""),!b("@"+g)&&b("@"+a.prefix+g)&&a.atrules.push(m);k.removeChild(e)})();a.valueProperties=["transition","transition-property"];k.className+=" "+a.prefix;StyleFix.register(a.prefixCSS)}})(document.documentElement); 
 

 

 

 
/** 
 
* Polyfill for the vw, vh, vm units 
 
* Requires StyleFix from -prefix-free http://leaverou.github.com/prefixfree/ 
 
* @author Lea Verou 
 
*/ 
 
var tt; 
 
(function() { 
 

 
if(!window.StyleFix) { 
 
\t console.log("out"); 
 
\t return; 
 
} 
 

 
// Feature test 
 
var dummy = document.createElement('_').style, 
 
\t units = ['vw', 'vh', 'vm'].filter(function(unit) { 
 
\t \t dummy.width = ''; 
 
\t \t dummy.width = '10' + unit; 
 
\t \t return !dummy.width; 
 

 
\t }); 
 

 
if(!units.length) { 
 
\t console.log("out2"); 
 
\t return; 
 
} 
 

 
StyleFix.register(function(css) { 
 
\t var w = innerWidth, h = innerHeight, m = Math.min(w,h); 
 
\t console.log(w); 
 
\t 
 
\t console.log("################## \t "); 
 
\t css =css.replace(/(\r\n|\n|\r)/gm,""); 
 
\t css =css.replace(/["']/g, "zzz") 
 
\t console.log(css); 
 
\t return css.replace(RegExp('\\b(\\d+(\.\\d+)?)(' + units.join('|') + ')\\b', 'gi'), function($0, num, d, unit) { 
 
\t \t console.log("hiiii"); 
 
\t \t switch (unit) { 
 
\t \t \t case 'vw':console.log($0);console.log(d);console.log(num);console.log(unit); 
 
\t \t \t \t console.log((num * w/100) + 'px'); 
 
\t \t \t \t console.log((num * w/100) + 'px'); 
 
\t \t \t \t return (num * w/100) + 'px'; 
 
\t \t \t case 'vh':console.log($0);console.log(d);console.log(num);console.log(unit); 
 
\t \t \t \t console.log((num * w/100) + 'px'); 
 
\t \t \t \t return num * h/100 + 'px'; 
 
\t \t \t case 'vm':console.log($0);console.log(d);console.log(num);console.log(unit); 
 
\t \t \t \t return num * m/100 + 'px'; 
 
\t \t } 
 
\t }); 
 
}); 
 

 
})();
/*test4.css*/ 
 

 
#testtarget1{ 
 
\t 
 
\t font-size:3vw; 
 
} 
 
#testtarget2{ 
 
\t 
 
\t font-size:5vw; 
 
} 
 
#testtarget3{ 
 
\t background:url("test.jpg"); 
 
\t font-size:7vw; 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <link rel='stylesheet' href='test4.css'/> 
 
</head> 
 

 
<body> 
 
    <div id='testtarget1'>Some text</div> 
 
    <div id='testtarget2'>Some text</div> 
 
    <div id='testtarget3'>Some text</div> 
 
    
 
    <script src="prefixfree.js"></script> 
 
    <script src="vunits.js"></script> 
 
    
 
</body> 
 
</html>

Заранее спасибо за любую помощь.

+3

Как вы получаете строку? Добавьте соответствующий код. Использование двойной кавычки внутри двойной кавычки - это синтаксическая ошибка, регулярное выражение не может помочь в этой ситуации. – Tushar

+0

Двойные кавычки вокруг 'background (" text.jpg ")' не являются ** реальными ** двойными кавычками, присутствующими в качестве символов в строке; они являются просто синтаксическим устройством для указания строкового литерала. Ваше регулярное выражение должно работать нормально, если у вас на самом деле есть «var a =» background (\ "text.jpg \") ";'. Что не работает? –

ответ

-1

Вот то, что вы ищете:

var a="background(\"text.jpg\")"; 
a = a.replace(/"/g, "||"); 
console.log(a); 

Выходы:

"background(||text.jpg||)"

Here is a JSBin.

Это потому, что replace возвращает новую строку.

+0

Не нужен флаг 'm'. Как это отличается от кода OP. – Tushar

+0

@ Tushar, может быть, я неправильно понял то, что он просил, но это, похоже, делает именно то, что задал вопрос? Замените двойную кавычку двойными трубами. – JosephGarrone

+0

'm' означает многострочный, не многократно. 'g' означает несколько раз (= все совпадения). 'm' не требуется в однострочной строке. – JJJ

Смежные вопросы