a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions.

Does anyone have suggestions on how to adjust the regular expression?


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
};

Answer №1

To enforce restrictions, you can incorporate anchors and look-ahead with alternatives:

var urlPattern = /^(?!.*(?:png|jpg)$)(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?$/gi;

  function replaceText(text, target) {
     var replacedText = text.replace(urlPattern, '<a target="' + target + '" href="$&">$&</a>');
     return replacedText;
  };

alert(replaceText("http://some.site.com/new/1.gif", "_blank"));
alert(replaceText("http://some.site.com/new/1.png", "_blank"));

The key component is ^(?!.*(?:png|jpg)$): it ensures the validation starts from the beginning of the string and confirms there are no occurrences of png or jpg at the end.

For lengthier strings containing URLs, consider using this regex pattern, which assumes URL strings do not contain spaces:

var urlPattern = /(?!\S*(?:png|jpg)(?:$|\s))(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angular-Resource instances throughout the entire application

Within my code, I have set up a straightforward resource of categories that utilizes a cached query action: app.factory 'Category', ($resource) -> $resource "/categories/:id", {id: '@id'}, { query: { cache: true, isArray: true, ...

Deactivate interactive functions on the mat-slider while preserving the CSS styling

I'm attempting to create a mat-slider with a thumb label that remains visible at all times. Below is my mat-slider component: <mat-slider class="example-margin" [disabled]="false" [thumbLabel]="true" [tickInterval]="tickInterval" ...

Utilize WebdriverIO to loop through elements and trigger a click event on a link

I am currently using Javascript and webdriverio (v2.1.2) for data extraction on an internal website. The process involves: Authentication Opening the necessary URL once authenticated Searching for an anchor tag with a specific keyword on the new page Cli ...

Assertion using Node.js with Selenium WebDriver

I am currently working on implementing assertions for testing using selenium webdriver with node js. However, I am encountering an issue where it returns undefined when trying to assert the page title (which is the URL of the page). It seems like I may n ...

Using Javascript to dynamically swap images within a div as the user scrolls

Can someone help me achieve a similar image scrolling effect like the one on the left side of this website: I am looking to change the image inside a div as I scroll and ensure that the page doesn't scroll further until all the images have been scrol ...

Struggling to understand the usage of FormData and ngResource

I am currently facing an issue while trying to upload a file as MIME/multipart through AngularJS 1.6.4 and then sending it to an ASP.Net WebAPI. I came across a sample project that uses version 1.3.1, where the following code snippet works: var formData ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Expanding Drop-Down Feature in CodeIgniter: How to Create Nested Dropdown Menus

I'm working on a dropdown menu that is populated with items using a foreach statement. When an item is selected, I need another dropdown menu to appear where specific items can be specified. First Dropdown - Categories (Completed) When a Category is ...

Python sends back a list containing garbled characters to Ajax

Need help fixing the output of a Python list returned to Ajax, as it appears strange. ap.py @app.route('/_get_comUpdate/', methods=['POST']) def _get_comUpdate(): comNr = request.form.get('comNr') com_result ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

Express.js Failing to Send Response Following POST Request

This is the function I have on the back end using express: // Function to register a new user exports.register_user = function(req, res) { var portalID = req.body.portalID; var companyName = req.body.companyName; var password = req.body.passwo ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

I was directed to https://code.angularjs.org/ due to an error in the AngularJS injector

Currently, I am utilizing angularjs and gulp for real-time updates when making changes. However, each time I encounter an error, I am redirected to https://code.angularjs.org/ to read about the specific error. Instead of having to constantly click on the ...

Struggling to implement my reusable React component within a React Bootstrap modal

I have developed a reusable textarea React component: import React from 'react'; import '../form-input/form-input.styles.scss'; const TextAreaComponent = ({ handleChange, label, ...otherProps }) => ( <div className="group"> ...

Is it possible to list bash/sh files as dependencies in package.json?

Currently, I have a bash script named publish.sh that I use for publishing modules to npm. Since I am constantly adjusting this script, I find myself needing to update every copy of it in each npm module I manage. Is there a method to include this bash sc ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

Vue table does not update when checkbox is unchecked

I am currently utilizing Daisy UI and basic VUE to create a checkbox functionality. When I check the checkbox, it successfully filters the table entries; however, when I uncheck or check another checkbox, the filter does not refresh again. Below is my tab ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

Utilizing ng-repeat and ng-if to display dynamic data fetched from the server

I have social media icons with a like button that turns red only if item.like== 1, or remains white if item.userid==0. I am updating this dynamically and need to call the function profileData() again when a user clicks the like button. However, every time ...