How to replace css('background-image') - javascript

I want to replace css('background-image') path.
The problem:
for the same variable oldBgImg = this.element.css('background-image')
FireFox returns -
"url("http://mySite/images/file1.png")"
but Chrome returns it without the quotes:
"url(http://mySite/images/file1.png)"
Here is the solution I use. can you please help me make it simpler?
var oldBgImg = this.element.css('background-image');
// => FF: "url("http://mySite/images/file1.png")"
// Chrome: "url(http://mySite/images/file1.png)"
// According to http://www.w3.org/TR/CSS2/syndata.html#value-def-uri :
// quotes are optional, so Chrome does not use them, but FF does . . .
var n1 = oldBgImg.lastIndexOf("("); n1 += 1; // now points to the char after the "("
var n2 = oldBgImg.lastIndexOf(")"); n2 -= 1; // now points to the char before the ")"
var c1 = oldBgImg.substring(n1, n1 + 1); // test the first Char after the "("
var c2 = oldBgImg.substring(n2, n2 + 1); // test the first Char after the "("
if ( (c1 == "\"") || (c1 == "\'") ) { n1 += 1; }
if ( (c2 == "\"") || (c2 == "\'") ) { n2 -= 1; }
var oldBgImgPath = oldBgImg.substring(n1, n2 + 1); // [ (" ] .. [ ") ]
var n = oldBgImgPath.lastIndexOf("/");
var newBgImgPath = oldBgImgPath.substring(0, n + 1) + "file2.gif";
// if needed, should also add :
// var path = encodeURI(newBgImgPath);
this.element.css('background-image', 'url(' + newBgImgPath + ')');
Notes:
According to http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
one can use single quote or double-quote or no quote sign
I am looking for a general solution, also for relative path (without "http" or with "file") , I just want to replace the fileName within the URL.

Here's an example of how to do it with regular expressions. - live demo
The expression:
("?)(http:.*?)\1\)
The match
url = 'url("http://mySite/images/file1.png")'.match(/("?)(http:.*?)\1\)/)[2];
You can then reconstruct your property.
$(this).css( 'background-image', 'url("' + url + "')" );
This should work on all browsers.

I did it with regular expressions. I use this code:
var re = /url\(['"]?(.+?)[^\/]+['"]?\)/;
var regs = re.exec(oldBgImg);
var newBgImgPath = regs[1] + "file2.png";
JSFiddle
I'll explain the RE.
It starts with a /, this will indicate it's a RE.
Then there's url\(. It matches the text url(. ( is escaped because it is a reserved character.
Then there is ['"]?. ['"] matches ' or " and the ? makes it optional.
A ( starts a RE group, that can be referred to.
In .+? . matches all charaters except a newline. A + tells that there must be at least 1 of them, or more. Finally, a ? makes the + non-greedy, so it matches as little characters as possible but still tries to match the whole RE.
A ) ends the group.
[^\/] matches any non-/ character. Then there's a + again. It has no ? after it, because we want to match as many non-/ characters (the file name) from the end as we can.
Finally, another optional quote, an escaped ) for the closing bracket in url(...) and a / to end the RE.
Now re.exec(oldBgImg) returns an array with the first element being the whole matched string and the next elements being the matched RE groups (created by () brackets). Then I can just take regs[1], which is the first matched group and contains the pathname.

You could replace the quotes in oldBgImg with nothing like this.
oldBgImg = oldBgImg.replace(/\"/g, "");
That way the URL is always the same no matter what browser retrieved it.

Related

Replace all “?” by “&” except first

I’d would to replace all “?” by “&” except the first one by javascript. I found some regular expressions but they didn’t work.
I have something like:
home/?a=1
home/?a=1?b=2
home/?a=1?b=2?c=3
And I would like:
home/?a=1
home/?a=1&b=2
home/?a=1&b=2&c=3
Someone know how to I can do it?
Thanks!
I don't think it's possible with regex but you can split the string and then join it back together, manually replacing the first occurance:
var split = 'home/?a=1?b=2'.split('?'); // [ 'home/', 'a=1', 'b=2' ]
var replaced = split[0] + '?' + split.slice(1).join('&') // 'home/?a=1&b=2'
console.log(replaced);
You could match from the start of the string not a question mark using a negated character class [^?]+ followed by matching a question mark and capture that in the first capturing group. In the second capturing group capture the rest of the string.
Use replace and pass a function as the second parameter where you return the first capturing group followed by the second capturing group where all the question marks are replaced by &
let strings = [
"home/?a=1",
"home/?a=1?b=2",
"home/?a=1?b=2?c=3"
];
strings.forEach((str) => {
let result = str.replace(/(^[^?]+\?)(.*)/, function(match, group1, group2) {
return group1 + group2.replace(/\?/g, '&')
});
console.log(result);
});
You can split it by "?" and then rewrap the array:
var string = "home/?a=1?b=2";
var str = string.split('?');
var new = str[0] + '?'; // text before first '?' and first '?'
for( var x = 1; x < str.length; x++ ) {
new = new + str[x];
if( x != ( str.length - 1 ) ) new = new + '&'; //to avoid place a '&' after the string
}
You can use /([^\/])\?/ as pattern in regex that match any ? character that isn't after / character.
var str = str.replace(/([^\/])\?/g, "$1&");
var str = "home/?a=1\nhome/?a=1?b=2\nhome/?a=1?b=2?c=3\n".replace(/([^\/])\?/g, "$1&");
console.log(str);

Javascript string trimming: Url and file path

Here comes javascript noob again.
What I would like to do. 1:
// I will have many URLs as input
// I want to check if URL NOT end with slash
// if not then trim string after slash
var given_URL = "http://www.test.com/test"
var trimmed_URL = "http://www.test.com/"
What I would like to do. 2:
// I will have many file paths
// I would like to check if the path starts with unwanted dot OR slash
// If so, I would like to trim it
var given_path_1 = "./folder/filename.xxx"
var given_path_2 = "/folder/filename.xxx"
var given_path_3 = ".folder/filename.xxx"
var trimmed_path = "folder/filename.xxx"
I would like to know how to achieve these.
Thanks in advance
For your first question, you should use the lastIndexOf method.
For example:
var index = given_URL.lastIndexOf("/");
Check if index === given_URL.length - 1 is true. If it is, you can use the slice method to cut your url.
For example:
var newUrl = given_URL.slice(0,index);
For your second question, you can check if given_URL[0] === "." or given_URL[0] === "/". If this is true, then use the slice method to slice it.
For example:
var newUrl = given_URL.slice(1, given_URL.length - 1);
You should try to use replace() using some regex:
//replace all "/*" at the end with "/"
given_URL.replace(/\/\w+$/,'/');
//replace all non letters at the start with ""
given_path_2.replace(/^\W+/,'');
To trim until the last forward slash /, you could find the last occurrence of it and check if it the last letter in the string. If it is, you take the string until after that last occurrence.
To remove an optional dot (\.?), followed by an optional forward slash (\/?) from the start (^) of a string, you could do a replace with a regex of ^\.?\/?.
function trimToLastForwardslash(input) {
var lastBackSlash = input.lastIndexOf('/');
return lastBackSlash != -1 && lastBackSlash != input.length - 1 ? input.substring(0, lastBackSlash + 1) : input;
}
function trimFirstDotOrForwardSlash(input) {
return input.replace(/^\.?\/?/, '');
}
var path = "http://www.test.com/test";
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path));
path = "http://www.test.com/test/";
console.log(path + ' => trim last slash => ' + trimToLastForwardslash(path));
path = "./folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));
path = "/folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));
path = ".folder/filename.xxx";
console.log(path + ' => trim first dot or slash => ' + trimFirstDotOrForwardSlash(path));

String that doesn't contain character group

I wrote regex for finding urls in text:
/(http[^\s]+)/g
But now I need same as that but that expression doesn't contain certain substring, for instance I want all those urls which doesn't contain word google.
How can I do that?
Here is a way to achieve that:
http:\/\/(?!\S*google)\S+
See demo
JS:
var re = /http:\/\/(?!\S*google)\S+/g;
var str = 'http://ya.ru http://yahoo.com http://google.com';
var m;
while ((m = re.exec(str)) !== null) {
document.getElementById("r").innerHTML += m[0] + "<br/>";
}
<div id="r"/>
Regex breakdown:
http:\/\/ - a literal sequence of http://
(?!\S*google) - a negative look-ahead that performs a forward check from the current position (i.e. right after http://), and if it finds 0-or-more-non-spaces-heregoogle the match will be cancelled.
\S+ - 1 or more non-whitespace symbols (this is necessary since the lookahead above does not really consume the characters it matches).
Note that if you have any punctuation after the URL, you may add \b right at the end of the pattern:
var re1 = /http:\/\/(?!\S*google)\S+/g;
var re2 = /http:\/\/(?!\S*google)\S+\b/g;
document.write(
JSON.stringify(
'http://ya.ru, http://yahoo.com, http://google.com'.match(re1)
) + "<br/>"
);
document.write(
JSON.stringify(
'http://ya.ru, http://yahoo.com, http://google.com'.match(re2)
)
);

Dynamic replace in regular expression scope

I need to rewrite some require paths in JavaScript source files:
Example (foo => ../../../foo/baz):
var a = require('foo/a'); => var b = require('../../../foo/baz/a');
var a = require('foo/../b'); => var b = require('../../../foo/baz/../b');
Note: This replacement will be done on a complete js source files. So require(' and ') must be used as delimiter!
So far we have figured out to use some setup like this:
var source = '';
source += "var a = require('foo/a');\n";
source += "var b = require('foo/../b');\n";
source += "console.log(a + b);";
var options = {
'foo': '../../../foo/baz'
};
for (var key in options) {
var regex = new RegExp('require[(](\"|\')' + key, 'g');
source = source.replace(regex, "require('" + options[key]);
}
console.log(source);
Though above source code is working. I am not sure if this is save as I am just skipping the closing delimiter.
I think this does it:
str = str.replace(/require\((['"])([^'"]*)foo\/([^'"]*)(['"])/g, "require($1$2../../../foo/baz/$3$4");
Here's that regex live: http://regex101.com/r/bE5jI4
Explanation:
require matches the characters require literally (case sensitive)
\( matches the character ( literally
1st Capturing group (['"])
['"] match either ' or " literally
2nd Capturing group ([^'"]*)
[^'"]* match a single character not present in the list below
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
'" a single character in the list '" literally
foo matches the characters foo literally (case sensitive)
\/ matches the character / literally
3rd Capturing group ([^'"]*)
[^'"]* match a single character not present in the list below
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
'" a single character in the list '" literally
4th Capturing group (['"])
['"] match ' or " literally
You may have to tweak it if there's optional whitespace before the opening quotes, or if your paths may contain ' or " characters. (In that latter case, you'll need two replacements, one when the wrapper quotes are ' and the other when they're ".)
This should work:
var source = '';
source += "var a = require('foo/a');\n";
source += "var b = require('foo/../b');\n";
source += "console.log(a + b);";
var options = {
'foo': '../../../foo/baz'
};
for (var key in options) {
var regex = new RegExp('(require)\\((["\'])(' + key + ')([^"\']*)\\2\\)', 'g');
source = source.replace(regex, "$1('" + options[key] + "$4')");
}
console.log(source);
OUTPUT:
var a = require('../../../foo/baz/a');
var b = require('../../../foo/baz/../b');
console.log(a + b);

remove 4 letters from a string, before the extension

How can you remove letters from a string in jquery
So for example if you had the following
var gif = "example_one.gif";
how could i out put it so it would show
"example.gif"
So remove the last four characters but keep the extension?
Regex approach
- Removes anything and including the underscore up until the extension
var gif = "example_one.gif";
gif = gif.replace(/(?=_).*(?=\.)/g,'');
DEMO
Explanation here
(?=_) Positive Lookahead - Assert that "underscore" can be matched
.* Matches any character (except newline)
(?=\.) Positive Lookahead - Assert that "period" can be matched
g modifier: Global. All matches (don't return on first match)
that what you want?
var gif = "example_one.gif" ;
gif = gif.substr(0, gif.indexOf("_")) + gif.substr(gif.indexOf("."), gif.length);
Walking through it the most basic way...
First find the .:
var gif = "example_one.gif";
var end = gif.lastIndexOf(".")
Then split the string:
var name_only = gif.substring(0,end)
Then take out what you want taken out:
var trimmed = name_only.substring(0,name_only.length-5)
Then put your extension back:
var cleaned = trimmed + gif.substring(end-1,gif.length)
Check it:
alert( cleaned )
Working fiddle: http://jsfiddle.net/digitalextremist/G27HN/
Or do it with a reusable function! http://jsfiddle.net/digitalextremist/wNu8U/
WITH ability to change length of trim job needed:
function cleanEnding( named, count ) {
if ( count == undefined ) count = 4
var end = named.lastIndexOf( "." )
var name_only = named.substring( 0, end )
var trimmed = name_only.substring( 0, name_only.length - count-1 )
var cleaned = trimmed + named.substring( end-1, named.length )
return cleaned
}
//de You CAN pass in a number after this.
//de The function defaults to trimming out 4 before the extension.
alert( cleanEnding( "example_one.gif" ) )
If its always the last four characters before the extension (and the extension is three characters):
var gif = "example_one.gif";
var gif2 = gif.substring(0, gif.length - 8) + gif.substring(gif.length - 4);
console.log(gif2);
http://jsfiddle.net/2cYrj/
var gif = "example_one.gif";
var str = gif.split('.');
str[0] = str[0].slice(0, -4);
gif = str.join('.');
console.log(gif);
var parts = gif.split('.');
var newstring = parts[0].substr(0, parts[0].length-4) + "." + parts[1];
gif.replace('_one', '')
Does this help you or you want it more general?
try this: gif.replace("_one","");

Categories

Resources