Develop a JavaScript regex pattern that can detect numbers that begin with a hashtag, while excluding any HTML special characters or pre-existing hyperlinks

I am attempting to generate links from specific strings. My current approach is:

([^&]#)([0-9]+)(?![^<>]*>)

However, the results are not entirely accurate.

Test 1: &#106
Test 2: #1040
Test 3: some text followed by #1060
Test 4: <a href="#1060">#1060</a>
Test 5: <b>#1078</b> (...or any other tag except <a>)
  • Test 1 & 4: should NOT match.
  • Tests 2, 3 & 5: should match.

The goal is to match a #number within any tag except for a link tag (and its attributes).

You can experiment with this in the following jsfiddle: http://jsfiddle.net/xqnjs2uq/3/

Considered as "regex3", the regex pattern plays an integral role alongside two others in achieving the desired outcome.

UPDATE Thanks to @chsdk's assistance, I've found a solution using two separate regex's (refer to regex3 and regex4 in the linked jsfiddle)...

http://jsfiddle.net/xqnjs2uq/6/

/[^&|href="]+(#[0-9]+\b)/gim  --> matches Test 3 and 5 above
/^(#[0-9]+)/   --> needed to match Test 2 

The ultimate challenge remains - Can this be condensed into a single regex?

Answer №1

Here is a regex pattern you can use: /[^&|href="](#[0-9]+)/g.

If you want to see it in action, check out this live demonstration, which provides results.

https://i.sstatic.net/do57l.png

It will match with the following:

https://i.sstatic.net/yMq4k.png

Update:

In case you need to exclude matching within links, here is the modified regex:

[^&|"](#[0-9]+\b)(?!<\/a>)

We included \b to ensure it captures the entire expression at a word boundary and (?!<\/a>) to prevent matching inside links.

You can test it again with this updated live demo, or try it out in this code snippet:

var re = /[^&|"](#[0-9]+\b)(?!<\/a>)/g;
var str = 'Test 1: &#106\nTest 2: #1040\nTest 3: some text followed by #1060\nTest 4: <a href="#1060">#1060</a>\nTest 5: <b>#1078</b> (...or any other tag except <a>)';
var m;

while ((m = re.exec(str)) !== null) {
  if (m.index === re.lastIndex) {
    re.lastIndex++;
  }
  document.write("<b>" + m[1] + "</b><br/>");
}

Answer №2

Experiment with this regex pattern:

(^(#|(<[b-zB-Z]+>))((0-9)+)(?!(<\/*a>*)))

Answer №3

Check out my solution below! Let me know if this is helpful.

/#[0-9]+/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

A Guide to Implementing v-for in a JSON Array with Vue.js

After receiving JSON data from the server: [ {"id":"2","name":"Peter","age":"24"}, {"id":"4","name":"Lucy","age":"18"}, ] I am ...

Reorganize array elements in a different sequence utilizing JavaScript

I possess an array const arr = [ {label: 'a', width: 200}, {label: 'b', width: 200}, {label: 'c', width: 200}, {label: 'd', width: 200}, {label: 'e', width: 200} ]; provided with another arr ...

Guide to updating the value of a CSS seconds dynamically

let timerSeconds = 10; // This value will be retrieved from a database function StartCountDownTimer() { let timerStart = new Date(); let css_seconds = `${timerSeconds}s`; const css_root = document.querySelector(':root'); let cssVa ...

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

Modifying ng-model after file selection in a directive

I have a unique directive that is able to detect changes in an input field of type file. When this change occurs, my goal is to then locate another input field and modify its ng-model. The issue I am facing is that I am unable to trigger the model change s ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

Transform XML2JS by eliminating square brackets around values

Currently, I am utilizing the xml2js node package for parsing an XML feed. Is there a method to avoid having the values enclosed in square brackets? For instance: "reference": ["ABC123"] should appear as "reference": "ABC123" "items": [ { "r ...

Utilizing npm packages from third-party sources within a custom extension for personal use (not intended for distribution)

Exploring the idea of developing a basic Firefox extension that involves external modules such as Firebase and Cheerio, but there doesn't seem to be much information available on this topic. I noticed there are legacy options like jpm, but they'r ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...

Ways to implement route path within Express

I am struggling to understand how the client file finds routes function in express. The structure of my app is as follows, |-root |--public |---files |---scripts |---css |--views ... The HTML on the client side is located in /public ...

A variable that can be changed is available within a closure in Angular services

Currently, I am working with the Angular UI grid library and facing an issue while populating a custom dropdown filter. This filter is only meant to be applied to specific columns, which is why I have implemented a for loop to dynamically access these colu ...

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...

How to Transfer Information Between Two React Components

I recently started learning React and I'm not sure how to approach this task. Basically, I have a list of cars and when the user clicks on each car, it should display detailed information about that specific car in a full-page slide. This is my curr ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

IE browser issue with includes() method

The code snippet I have been using works flawlessly in browsers like Chrome, Firefox, and Edge. However, upon testing it in IE11, I noticed that it does not work as expected and breaks some functionality. var href = jQuery(this).attr('href'); if ...

Pattern match to exclude specific characters in MongoDB

Currently, I am exploring mongodb and experimenting with Regex. As part of my work, I executed the following query: { "email": /@/ } Now, I am trying to figure out how to express this in a different way: { "email": does not have @ } I would be g ...

Is there a way to showcase uploaded images as a deck of cards in a react.js application?

One of the features on my website allows users to upload photos, which are then displayed in the browser. I am looking for a way to enable other users who log in later to see these uploaded photos by clicking a 'next' or 'previous' but ...

Substitute HTML data attributes

Hey everyone, I'm wondering how to change a data attribute in my code. For example, I am currently using a script for a video background, but I want to replace the video with a lighter version when viewed on a mobile device. In my JavaScript file, I h ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...