JavaScript - Regular expression to convert image source - javascript

My question is related only to JavaScript regular expressions.
I'm building a simple Lightbox for Wordpress with Mootools JavaScript framework.
Wordpress stores pictures in a variety of sizes with file names like:
'image-50-50x100.jpg'
'image-50-150x100.jpg'
'image-50-1024x698.jpg'
'image-50.jpg'
When a user clicks a thumbnail image, I have to convert the source of that image into the source of full size image, and then preload that full-size image.
The question
How to change string like this:
'http://some-path/image-50-50x100.jpg'
'http://some-path/image-50-150x100.jpg'
'http://some-path/image-50-1024x698.jpg'
'http://some-path/image-50.jpg'
, into:
'http://some-path/image-50.jpg'
Missing piece is accurate regular-expression in code below:
source.replace( /regular-expression/, '' );
Thanks in advance.

This should do it:
str = str.replace(/-\d+x\d+/, '');
E.g.:
var str = 'http://some-path/image-50-1024x698.jpg';
str = str.replace(/-\d+x\d+/, '');
console.log(str); // "http://some-path/image-50.jpg"
And for the case where you don't want it to change, it doesn't:
var str = 'http://some-path/image-50.jpg';
str = str.replace(/-\d+x\d+/, '');
console.log(str); // "http://some-path/image-50.jpg"
Edit: You've said in a comment elsewhere that:
In some rare cases it can happen that Wordpress user uploads image like image-1024x698.jpg, then Wordpress creates thumb image like image-1024x698-300x300.jpg
Okay, so we add \. and . to the above:
var str = 'http://some-path/image-1024x698-300x300.jpg';
str = str.replace(/-\d+x\d+\./, '.');
console.log(str); // "http://some-path/image-1024x698.jpg"

Try:
source.replace(/(.+\/[^-]+-[^-]+)(-\d+x\d+)*\.([^\.]+)$/, '$1.$3')

Related

JavaScript function to identify URL and make them clickable

I have a requirement , my client send me a string. for the links he is sending link title in squre brackets and link with bracket. like below,
[Google](https://www.google.com/)
I need get that value and make it clickable Google . adding like below and replace that to the original text.
' + url + ''
can anyone suggest better way of doing this with JavaScript regex.
Looks like Markdown formatting, so you could use a markdown library like Marked to parse and render it:
const s = '[Google](https://www.google.com/) ';
document.getElementById('content').innerHTML = marked(s);
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="content"></div>
Can be done with String replace function.
Regex: /\[(.*)\]\s*\((.*)\)/g
Replacer: $1
const str = `Lorem ipsum. [Google](https://www.google.com/). Sample text.`
const output = replaceWithLinks(str);
console.log(output);
function replaceWithLinks(str) {
return str.replace(/\[(.*)\]\s*\((.*)\)/g, '$1')
}
In HTML file:
<h1 id="header"></h1>
In Js File:
const myString = "[Google](https://www.google.com/)";
const show = myString.match(/\[(.*?)\]/); // it return two things. The first is with bracket and the second one is without bracket you have to use without bracket.
const url = myString.match(/\((.*?)\)/);
document.getElementById("header").innerHTML = `${show[1]}`;
You have to use regular expression. To get information about regular expression read MDN.
Get the first index value and show it to the UI.
Regexp is very handy for this purpose. just copy below code to F12 console for a preview
"text before [Google](https://www.google.com/) and after".replace(/\[(.*?)\]\((.*?)\)/gm, '$1')
ps: the code copy from a simple markdown parser

JavaScript regex test not begening with attribute

I'm trying to test words string which don't begin with a specific word,
var content = 'special-src="http://www.link.com" ';
var src = new RegExp(/\b(?!special-)\w*src=*\b/g);
console.log(src.test(content));
This should console a false, but it's not.
But, if I remove the - from the regex and content, the result is fine so I guess this is kind of escaping issue ?
What you're looking for is a negative lookbehind (?<!special-), not negative lookahead (?!special-). I've got it working in Regex Workbench, but Javascript doesn't support this natively.
This approach looks like it might work: http://davidchin.me/blog/simulate-regex-lookbehind-in-javascript/
Try with:
var content = 'special-src="http://www.link.com" ';
var src = /^(?!special\-)\w*src=.*$/g;
console.log(src.test(content));
UPDATE
There was a mistake in the expression, should be !? instead ?!. The correct code is
var content = 'special-src="http://www.link.com" ';
var src = /^(!?special\-)\w*src=.*$/g;
console.log(src.test(content));

Auto-link URL with javascript Regex

I have a paragraph of text which may contain some links in plain text, or some links which are actually links.
For example:
Posting a link: http://test.com, posting an image <img src="http://test.com/2.jpg" />. Posting an actual A tag: http://test.com/test.html
I need to fish out the unformatted links from this piece of text. So any regular expression that will match the first case, but not the second or third case because they are already well formatted links.
I've managed to fish out all the links with this regex: ((http:|https:)\/\/[a-zA-Z0-9&#=.\/\-?_]+), however, am still having trouble distinguishing between the cases.
This needs to be in javascript so I don't think negative lookbehind is allowed.
Any help would be appreciated.
EDIT: I'm trying to wrap the fished out unformatted links in an a tag.
You can use this regex to get URLs outside of tags:
(?![^<]*>|[^<>]*<\/)((http:|https:)\/\/[a-zA-Z0-9&#=.\/\-?_]+)
See demo
We can shorten it a bit, too, with an i option:
(?![^<]*>|[^<>]*<\/)((https?:)\/\/[a-z0-9&#=.\/\-?_]+)
See another demo
Sample code:
var re = /(?![^<]*>|[^<>]*<\/)((https?:)\/\/[a-z0-9&#=.\/\-?_]+)/gi;
var str = 'Posting a link: http://test.com, posting an image <img src="http://test.com/2.jpg" />. Posting an actual A tag: http://test.com/test.html';
var val = re.exec(str);
document.getElementById("res").innerHTML = "<b>URL Found</b>: " + val[1];
var subst = '$1';
var result = str.replace(re, subst);
document.getElementById("res").innerHTML += "<br><b>Replacement Result</b>: " + result;
<div id="res"/>
Update:
To allow capturing inside specific tags, you can whitelist them like this:
var re = /(?![^<]*>|[^<>]*<\/(?!(?:p|pre)>))((https?:)\/\/[a-z0-9&#=.\/\-?_]+)/gi;

If string matches regex replace, if not add variable

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

How to use href.replace in extjs

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

Categories

Resources