How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #).

The input data I have is

This is my amazing message with a stock $symbol that I need to click on

and what I need back (in string format) is

This is my amazing message with a stock

<a href ='https://stocktwits.com/symbol' target='_blank> $symbol </a>
that I need to click on

When rendered, only the $symbol should be clickable within the anchor tag.

If it helps, I have an array of symbols that will appear in every message without the $ sign.

Currently, I'm attempting this process in react but it's quite messy and I'm struggling to get it right.

//Message incoming is: 'This is my amazing message with a stock $symbol that I need to click on'
const message_body = unescape(this.props.data.body)

//find words to replace. Output is ['symbol1', 'symbol2', 'symbol3']
let find = [];
for(let symbl of this.props.data.symbols){
  find.push(symbl.symbol)

}

//set values for replacement
let replace = [];
for(let symbl of find){
  let url = `https://stocktwits.com/${symbl}`
  let link = `<a href=${url} target="_blank">${symbl}</a>`
  replace.push(link)

}

//using the replace-once library, replacing words in the message
let formed_message = replaceOnce(message_body, find, replace, 'gi')

...... 

//using react-html-parser to convert the <a href> tags into a clickable link
<Card.Text>{ReactHtmlParser(formed_message)}</Card.Text>

The expected output is

This is my amazing message with a stock $symbol that I need to click on

The $ is not included in the link, and only symbols preceded by a $ sign should be linked. For example,

$GOOG $SPY $AAPL off topic. Good job GOOGle!

In the above message, only GOOGL should be turned into a link as it starts with a $.

As mentioned, the code is complex and I'm almost there but open to any suggestions or improvements. Thank you!

Answer №1

Here is a suggested solution for you:

let modified_message = this.props.data.symbols.map({symbol} = symbol).reduce(
      (p, s) => p.replace(`$${s}`, `<a href ='https://stocktwits.com/${s}' target='_blank> $${s}</a>`), 
      message_body
)

const message_body = "I have a great message with symbols like $symbol and I want to link them to their stock pages such as $symbol2";

console.log(['symbol', 'symbol2', 'symbol3'].reduce(
      (p, s) => p.replace(`$${s}`, `<a href ='https://stocktwits.com/${s}' target='_blank> $${s}</a>`), 
      message_body
))

Answer №2

If you want to find all words that come after a dollar sign in a text, using a regular expression can help you achieve that.

const sentence = 'I have $10 in my pocket but I need more for the concert';
const result = sentence.replace(/\$(\w+)/g, (match, word)=>
   `<a href ='https://example.com/${word}' target='_blank> ${match} </a>`);
console.log(result);

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

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Jump straight to the top of the page with just a click using the Google Maps Store Locator

When I use my Store Locator and click on an anchor like "Zoom Here," "Directions," or "Street View," the href hash always brings me back to the top of the page. How can I prevent this from happening? I've tried examining the minified source code for t ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

Mocha maintains the integrity of files during testing

After running a unit test to update a config file, I noticed that the file was altered. My initial thought was to use "before" to cache the file and then restore it with "after". mod = require('../modtotest'); describe('Device Configuratio ...

Determine the number of input tags within a div element by utilizing the closest property in jQuery

Sorry for the silly question, but I've been struggling to find a solution. Spent hours scratching my head. Here is my HTML structure: <div class= 'container'> <div class="someclass"> <input>some content</in ...

What steps do I need to take in order to transform this code into a MUI component complete with

Having some trouble converting my hero banner code to MUI in a React project. The styling is not coming out correctly. Here is the HTML code: <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120 ...

Is there a way to retrieve the total count of the selected options using Autocomplete in material-ui?

Is there a way to show the total count of chosen options using the Autocomplete feature from material-ui? If so, how can I achieve this? Simply follow these steps: click on Open menu dropdown, open the Autocomplete, select your desired options, and you w ...

Experiencing unfamiliar typescript glitches while attempting to compile a turborepo initiative

I have been utilizing the turborepo-template for my project. Initially, everything was running smoothly until TypeScript suddenly started displaying peculiar errors. ../../packages/fork-me/src/client/star-me/star-me.tsx:19:4 nextjs-example:build: Type erro ...

Develop a React component library and seamlessly integrate it into a Next.js project

Currently, I am in the process of building a component library using react js, vite tailwindcss, and antd. The components function flawlessly when running the project locally or within Storybook. However, upon importing them into another nextjs application ...

Switch up the positioning of elements using jQuery

My webpage contains multiple elements that are absolutely positioned with the CSS attribute "top." I am looking to adjust the top position of each element by 20px. This involves retrieving the current top position and adding 20px to it. The quantity of e ...

Provide the option to assign values on select options in order to choose specific JSON data

When working with JSON data from an API, I am creating a dynamic select element. The goal is to change some content (text and image src) based on the option selected from this select element. I have successfully populated the select options with names usi ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...

Developing a sliding menu with AngularJS

Currently, I am developing an AngularJS application. One of the features I am working on involves having a menu at the top of my page that, when an item is selected, will slide down to reveal content specific to that selection in the same area as the menu. ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...

Organizing a set of div elements based on their ID attributes

I am faced with the challenge of sorting a list of divs based on their ID values, which are in the format "indexNumber123". Instead of arranging them alphabetically, I want to sort them numerically as "indexNumber1", "indexNumber2", "indexNumber3" before d ...

What is the right way to implement email validation using Regex in a ReactJS application?

Currently in my ReactJS JSX code, I am attempting to create a regex validation for an email field without relying on any external dependencies such as Validator. Here is the snippet of code that I have been working with: isEmailInvalid = ({ email }) => ...

Retain the existing HTML files of the old website on the webserver while preventing search engines from indexing them

Recently, I completed a website for a client who is looking to replace their ancient HTML hard-coded website. The challenge lies in the fact that they wish to preserve the old website and its files on the web server at their current location. While this do ...

Dealing with menu overflow in React using Material UI

Is there a way to ensure that the main content moves correctly in this scenario? Perhaps I need to dynamically calculate the margin-left or find a better solution altogether? Initially, everything seems fine: https://i.stack.imgur.com/S7WBd.png However, ...