regular expression to replace links - javascript

I have following code to create html links in a plain text. This works fine but the link should not contain .png or .jpg
Any suggestions in adapting the regexp?
var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/gi;
return function(text, target) {
var replace = text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>');
return replace
};

You can add anchors and a look-ahead with alternatives to add the restriction:
var urlPattern = /^(?!.*(?:png|jpg)$)(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?$/gi;
function repl (text, target) {
var replace = text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>');
return replace;
};
alert(repl("http://some.site.com/new/1.gif", "_blank"));
alert(repl("http://some.site.com/new/1.png", "_blank"));
The crucial part here is ^(?!.*(?:png|jpg)$): it makes the check start at the beginning of a string, and makes sure there is no png nor jpg at the end.
If you pass longer strings with URLs inside, you can use the following regex that assumes you have no spaces in your URLs:
var urlPattern = /(?!\S*(?:png|jpg)(?:$|\s))(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/gi;

Related

Convert Text into Hyperlinks <a> and Image tags <img>

I am using this function to convert text into clickable links ( ) and image urls into img tags (<img src="" />).
const parsecontent = (text)=>{
var ishyperlink= /([^\S]|^)((https?\:\/\/)(\S+))/gi;
return (text || "").replace(ishyperlink,
function(match, space, url){
var isimglink = /https?:\/\/.*\.(?:png|jpg|gif|jpeg)/i;
if (url.match(isimglink)) {
return space + '<img src="' + url + '" />';
}
return space + '' + url + '';
}
);
}
Using like this
const div = document.querySelector("#content");
div.innerHTML = parsecontent(div.innerHTML);
It works fine, if the content with proper spaces. It links, image urls not separated with spaces it fails. Can you pls help me to fix this?
Codepen here https://codepen.io/dagalti/pen/GRqpYLp
I came up with a regex that's tailored to satisfy your test cases.
This regex is how we will match for a URL:
((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))
In your example, we have 2 urls together with no whitespace in between. What happens if we have a url and a non-url string with no whitespace between? We could terminate the match when it reaches a TLD (such as .com, .org, etc). To satisfy your example however, I am making the assumption that we are dealing with 2 urls separated by no whitespace. In that case, we want to terminate the match when we notice the start of a new url (?=https?):
([^\S]|^)((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))(?=https?)
Next we want to match the urls that are surrounded by whitespace:
((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))
Putting all this together we get this regex:
([^\S]|^)((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))(?=https?)|((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))
We have to adjust your replace logic a bit too:
const parsecontent = (text)=>{
var ishyperlink= /([^\S]|^)((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))(?=https?)|((https?\:\/\/)([\w!"#$%&\'()*+,-./#:;=\^_`{|}~]*))/gi;
return (text || "").replace(ishyperlink,
function(url){
var isimglink = /https?:\/\/.*\.(?:png|jpg|gif|jpeg)/i;
if (url.match(isimglink)) {
return '<img src="' + url + '" />';
}
return '' + url + '';
}
);
}
This regex is quite verbose, there may be more succinct ways of satisfying your test cases (I'm not a regexpert though)

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

Replace ID in a URL between two markers

I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";

Javascript regex urls that are not image extensions

I've got the following JavaScript which matches and replaces URLS with html links, however I need this to exclude urls which end in .png|.jpg|.jpeg|.gif
text = text.replace(
/(\b(?:https?|ftp):\/\/[a-z0-9-+&##\/%?=~_|!:,.;]*[a-z0-9-+&##\/%=~_|])/gim,
'$1'
);
You could just to a test before:
if (!text.match(/\.(png|jpg|jpeg|gif)$/) {
text = text.replace(
/(\b(?:https?|ftp):\/\/[a-z0-9-+&##\/%?=~_|!:,.;]*[a-z0-9-+&##\/%=~_|])/gim,
'$1'
);
}
If you need to do multiple replacements, then you could use a custom replace function that checks the match against the image endings and acts accordingly. That would work like this:
var imageRegex = /\.(png|jpg|jpeg|gif)$/;
text = text.replace(/(\b(?:https?|ftp):\/\/[a-z0-9-+&##\/%?=~_|!:,.;]*[a-z0-9-+&##\/%=~_|])/gim,
function(str) {
if (str.match(imageRegex)) {
return(str);
} else {
return('' + str + '');
}
});

Converting text into a link with JavaScript returns an error

function assert() {
document.write.apply(document, arguments);
}
var testLink = "google.com";
function makeIntoLink(link) {
if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
link.replace(link, "<a href=\"http://www." + link+ "\">" + link + "<\/a>");
}
return link;
}
assert(makeIntoLink(testLink));
It writes it down but not in link form. Just "google.com" without the link. What could've gone wrong?
A function like link.replace doesn't actually replace stuff inside the string, it actually returns a NEW string with the replacements made. For example:
function replaceText() {
var searchText = ".com";
var link = "google.com";
var newLink = link.replace(searchText, ".co.uk");
alert(link); // Output = "google.com"
alert(newLink); // Output = "google.co.uk"
}
In your situation though, you don't need to use string.replace(...) at all, instead you can just do this:
function makeIntoLink(link) {
if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
//link.replace(link, "<a href=\"http://www." + link+ "\">" + link + "<\/a>"); <-- OLD
link = "<a href=\"http://www." + link+ "\">" + link + "<\/a>"; // <-- NEW
}
return link;
}
link.replace doesn't change the text in-situ, it makes a new string. Trying changing the line from link.replace(link... to link = link.replace(link...
replace returns a version of the string with the replacement made; the string is not replaced in-situ. So link = link.replace... rather than simply link.replace.
As the others have said, replace doesn't change the variable, it just returns a new one. But in this case, you don't really want to replace something, you just want to concatenate some stuff around it.
IMO, you don't need the replace function for that:
function makeIntoLink(link) {
if (link.match(/^[a-zA-Z0-9]+(.com)/)) {
link = '' + link + '';
}
return link;
}
(I've also removed your \" escapes by using different quote characters for the JS string literal and the HTML attributes. This makes it a mite less hard to read, IMHO).

Categories

Resources