I'm using javascript to append a string to a variable (adding specific image size to a slider on mobile devices).
Here's the line I'm using.
var newsrc = src.substring(0, src.lastIndexOf(".")) + "-420x320" + src.substring(src.lastIndexOf("."));
However there are some cases where the image src has another size and in this case I would like to remove that size and add the one above.
Example:
Both
http://domain.com/10001428289243jpg-700x703.jpg and
http://domain.com/10001428289243jpg.jpg
Needs to be:
http://domain.com/10001428289243jpg-420x320.jpg
What would you use in this case?
All you need is to build a pattern with an optional part:
src = src.replace(/(?:-\d+x\d+)?\.jpg$/, '-420x320.jpg');
where (?:-\d+x\d+)? is an optional non-capturing group and $ is an anchor for the end of the string.
FIDDLE LINK: http://jsfiddle.net/9u8m9oob/1/
You can achieve the same using below way also:
var str1='http://domain.com/10001428289243jpg.jpg';
var str2='http://domain.com/10001428289243jpg-700x703.jpg';
var regex=/^(http:\/\/domain\.com\/)(\d+jpg)(.)*(\.jpg)$/g;
var result= str1.replace(regex,"$1$2-420x320$4");
console.log(result); // gives output as http://domain.com/10001428289243jpg-420x320.jpg
I'd stick in a quick replace that matches the -#x# pattern and replaces it with a blank.
var newsrc = src.replace(/(-\d+x\d+)/,"").substring(0, src.lastIndexOf(".")) + "-420x320" + src.substring(src.lastIndexOf("."));
Related
How do I remove the image resolution from the string below in Node.js?
http://asset.beyonce.com/wp-content/uploads/2016/06/XIII6614-800x800.jpg
I'd like it to be just
http://asset.beyonce.com/wp-content/uploads/2016/06/XIII6614.jpg
without the -800x800!
var image = 'http://asset.beyonce.com/wp-content/uploads/2016/06/XIII6614-800x800.jpg';
image = image.replace(new RegExp("^(.*?)-\d+x\d+\.([^/]+)$", "g"), "")
console.log(image);
The above code isn't working for some reason?
var image = 'http://asset.beyonce.com/wp-content/uploads/2016/06/XIII6614-800x800.jpg';
image = image.replace(/^(.*?)(-\d+x\d+)(\.[^/]+)$/, "$1$3");
console.log(image);
You can use this regex, refering to matched groups when replacing.
Your regex is matching the url up-to the dash and .jpg. And the replace will remove everything except -800x800.
Please have a look here for the result of the regex.
You could use regex.match and join the result. Or use a regex replace like this:
image = image.replace(new RegExp("-\d+x\d+", "g"), "")
The main problem is that the regex isn't fulfilling what you want it to do.
Also note that new RegExp is a bit overkill as you can just define it right away within forward slashes.
Below code should help.
var image = 'http://asset.beyonce.com/wp-content/uploads/2016/06/XIII6614-800x800.jpg';
image = image.replace(/-\d+x\d+\./g, "")
console.log(image);
Firstly your regexp match the whole string, so you should get an empty result.
Then you don't need the "g" as it matches multiple times, and you just need to remove the part at the end of the URL.
And last, you have to put in the substitution string the saved file extension.
Use regexp literal:
image = image.replace(/-\d+x\d+\.([^/]+)$/, ".$1");
Don't forget the $ char at the end of the regexp.
I need to be able to grab the number at the end of the url, and set it as the value of a textbox. I have the following, but it's not correctly stripping out the beginning of the URL before the last slash. Instead, its doing the opposite.
<input id="imageid"></input>
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var assetID = referrerURL.match("^(.*[\\\/])");
$("#imageid").val(assetID);
The result of the regex match should set the value of the text box to 750 in this case.
JSFiddle: Link
The simple method is to use a negated character class as
/[^\/]*$/
Regex Demo
Example
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
alert(referrerURL.match(/[^\/]*$/));
// Output
// => 750
Can use a simple split() and then pop() the resultant array
var assetID = referrerURL.split('/').pop();
Easier to read than a regex thus very clear what it is doing
DEMO
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var myregexp = /.*\/(.*?)$/;
var match = myregexp.exec(referrerURL);
$("#imageid").val(match[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="imageid"></input>
You could try avoiding the usage of regular expression for this task just by using native javascript's string functions.
Splitting the text:
var lastSlashToken = referrerURL.split("/").pop(-1);
Looking up for the last ending "/text" token:
var lastSlashToken = referrerURL.substr(referrerURL.lastIndexOf("/") + 1);
However, if you still want to use regular expression for this task, you could try using the following pattern:
.*\/([^$]+)
Working DEMO example # regex101
I have an <img> tag inside a div where i want to get the image name through javascript and regex.
Now, I successfully retrieved the <img> tag as a string.
var bigImage = $(this).find('.img-container img')
var bigImageSrc = bigImage[0].src
var regx = /g\bplaceholderdefault\.jpg?\b/g
var match = bigImageSrc.match(regx)
I want this expression to see if there is placeholderdefault.jpg in the string.
By the way, bigImageSrc returns a valid string, as I checked it with typeof
Now the problem is it returns null even if bigImageSrc's value is http://localhost/yogurtbar/images/slider/placeholderdefault.jpg
I don't get why it doesn't detect placeholderdefault.jpg in the string. I tried (and produced) this regular expression in Regexr and it works.
What am I doing wrong in my code?
There is no need of regex.\
You can use indexOf. This will run faster as compared to regex:
if (bigImageSrc.indexOf('placeholderdefault.jpg') > -1) {
// Present
If you want to check it with regex:
if (/placeholderdefault\.jpg/.test(bigImageSrc)) {
// Present
}
You need to escape .
You need to remove the g present at the start.
var regx = /g\bplaceholderdefault\.jpg?\b/g;
^
|
Since there isn't a charcater g exists before p (in placeholder), your regex fails to find a match.
correct one would be,
var regx = /\bplaceholderdefault\.jpg?\b/g;
and also, I think you want to match both jpg and jpeg formats.
var regx = /\bplaceholderdefault\.jpe?g\b/g;
Easy way will be to get the image name using split()
var bigImageSrc = 'http://localhost/yogurtbar/images/slider/placeholder-default.jpg';
var filename = bigImageSrc.split("/").pop();
console.log(filename);
//output placeholder-default.jpg
I have some text content (read in from the HTML using jQuery) that looks like either of these examples:
<span>39.98</span><br />USD
or across multiple lines with an additional price, like:
<del>47.14</del>
<span>39.98</span><br />USD
The numbers could be formatted like
1,234.99
1239,99
1 239,99
etc (i.e. not just a normal decimal number). What I want to do is get just whatever value is inside the <span></span>.
This is what I've come up with so far, but I'm having problems with the multiline approach, and also the fact that there's potentially two numbers and I want to ignore the first one. I've tried variations of using ^ and $, and the "m" multiline modifier, but no luck.
var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");
var strPrice = strContent.replace(strRegex, '$1');
I could use jQuery here if there's a way to target the span tag inside a string (i.e. it's not the DOM we're dealing with at this point).
You could remove all line breaks from the string first and then run your regex:
strContent = strContent.replace(/(\r\n|\n|\r)/gm,"");
var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");
var strPrice = strContent.replace(strRegex, '$1');
This is pretty easy with jQuery. Simply wrap your HTML string inside a div and use jQuery as usual:
var myHTML = "<span>Span 1 HTML</span><span>Span 2 HTML</span><br />USD";
var $myHTML = $("<div>" + myHTML + "</div>");
$myHTML.find("span").each(function() {
alert($(this).html());
});
Here's a working fiddle.
try using
"[\s\S]*<span>(.*?)</span>[\s\S]*"
instead of
".*<span>(.*?)</span>.*"
EDIT: since you're using a string to define your regex don't forget to esacpe your backslashes, so
[\s\S]
would be
[\\s\\S]
You want this?
var str = "<span>39.98</span><br />USD\n<del>47.14</del>\n\n<span>40.00</span><br />USD";
var regex = /<span>([^<]*?)<\/span>/g;
var matches = str.match(regex);
for (var i = 0; i < matches.length; i++)
{
document.write(matches[i]);
document.write("<br>");
}
Test here: http://jsfiddle.net/9LQGK/
The matches array will contain the matches. But it isn't really clear what you want. What does there's potentially two numbers and I want to ignore the first one means?
how to use href.replace in extjs
This is my sample:
'iconCls': 'icon_' + href.replace(/[^.]+\./, '')
href= http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png
Now i want to get text "release_history.png", How i get it.
Thanks
If you just want the filename, it's probably easier to do:
var href = "http://localhost:1649/SFM/Default.aspx#/SFM/config/release_history.png";
var iconCls = 'icon_' + href.split('/').pop();
Update
To get the filename without the extension, you can do something similar:
var filename = "release_history.png";
var without_ext = filename.split('.');
// Get rid of the extension
without_ext.pop()
// Join the filename back together, in case
// there were any other periods in the filename
// and to get a string
without_ext = without_ext.join('.')
some regex solutions (regex including / delimiter)
as in your example code match the start of the url that can be dropped
href.replace(/^.*\//, '')
or use a regex to get the last part of the url that you want to keep
/(?<=\/)[^.\/]+\.[^.]+$/
update
or get the icon name without .png (this is using lookbehind and lookahead feature of regex)
(?<=\/)[^.\/]+(?=\.png)
Not all flavors of regex support all lookaround reatures and I think Javascript only supports lookahead. so probably your solution is this:
[^.\/]+(?=\.png)
code examples here:
http://www.myregextester.com/?r=6acb5d23
http://www.myregextester.com/?r=b0a88a0a