Using JavaScript, you can employ the .split() and .replace() methods on a string value to accurately extract the specific

I'm currently attempting to extract hashtags from a text string by splitting it and removing unwanted HTML tags.

Despite my efforts, I haven't been able to achieve the desired outcome. I am seeking guidance on where I might be going wrong.

Here is an example of the text string:

"<a href=\"https://twitter.com/search?q=fnb\" target=\"_blank\">#fnb</a>, <a href=\"https://twitter.com/search?q=mobilesimcard\" target=\"_blank\">#mobilesimcard</a>, <a href=\"https://twitter.com/search?q=what\" target=\"_blank\">#what</a>, <a href=\"https://twitter.com/search?q=refugeechild\" target=\"_blank\">#refugeechild</a>"

This is the code snippet I've written so far:

var str = "<a href=\"https://twitter.com/search?q=fnb\" target=\"_blank\">#fnb</a>, <a href=\"https://twitter.com/search?q=mobilesimcard\" target=\"_blank\">#mobilesimcard</a>, <a href=\"https://twitter.com/search?q=what\" target=\"_blank\">#what</a>, <a href=\"https://twitter.com/search?q=refugeechild\" target=\"_blank\">#refugeechild</a>";

var array = [];
var parts = str.split('target=\"_blank\">', '');

parts.forEach(function (part) {
var rem1 = part.replace('</a>', '');
array.push(rem1)
})
var value = array;
console.log(value);

The expected output should be: #fnb, #mobilesimcard, #what, #refugeechild

It seems that my str.split() method isn't functioning as intended, and I suspect I may need to improve upon the .replace() function as well.

Appreciate any assistance you can provide!

Answer №1

Utilizing a regular expression to find hashtags:

var str = "<a href=\"https://twitter.com/search?q=fnb\" target=\"_blank\">#fnb</a>, <a href=\"https://twitter.com/search?q=mobilesimcard\" target=\"_blank\">#mobilesimcard</a>, <a href=\"https://twitter.com/search?q=what\" target=\"_blank\">#what</a>, <a href=\"https://twitter.com/search?q=refugeechild\" target=\"_blank\">#refugeechild</a>";
var array = str.match(/#[a-z-_]+/ig)

console.log(array);

This particular regex is quite basic, there are much more sophisticated ones available, such as Best HashTag Regex

Answer №2

Utilize the map() method for arrays :

See it in action :

var str = "<a href=\"https://twitter.com/search?q=fnb\" target=\"_blank\">#fnb</a>, <a href=\"https://twitter.com/search?q=mobilesimcard\" target=\"_blank\">#mobilesimcard</a>, <a href=\"https://twitter.com/search?q=what\" target=\"_blank\">#what</a>, <a href=\"https://twitter.com/search?q=refugeechild\" target=\"_blank\">#refugeechild</a>";

var resArray = [];
var parts = str.split('</a>');

var array = parts.map(function(item) {
  return item.split('>')[1];
});

for(var i = 0; i < array.length-1; i++) {
  resArray.push(array[i]);
}

var value = resArray;
console.log(value);

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

Issues with lazy loading in swiper.js when trying to display multiple images per slide

I recently tried using swiper.js and had success with the lazy loading demo. However, I encountered an issue where only one image per slide was showing up, despite wanting to display 4 images per slide. <div class="swiper-container"> <div cla ...

Using Angular to iterate over JSON fields containing hyphens

<span ng-repeat="doc in docs"> <p>{{doc.posted-Time}}</p> Instead of the actual value from the JSON, all I am getting is a 0. Is there a method to avoid this issue with the '-'? In my normal practice, I would utilize doc[&a ...

JSX refusing to display

Currently, I am enrolled in an online course focusing on React and Meteor. Despite successfully registering a new player in the database upon hitting the submit button, the client side fails to display the information. Upon checking the console, the foll ...

Utilizing express.js alongside the native MongoDB driver: A comprehensive guide

I'm facing difficulties when attempting a simple mongoDB query from my express app: app.js var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = re ...

I am encountering issues with my THREE.js RawShaderMaterial

I haven't encountered any issues when loading shaders created by others into THREE.js, but I've hit a roadblock when trying to create and run my own shader. The shader works perfectly on the platform where I designed it (), but it doesn't fu ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

Problem with the datepicker in mgcrea.ngStrap

Encountering an issue with the datepicker feature from the mgcrea.ngStrap library. Here is a glimpse of my layout file setup: <html lang="en-US" ng-app="ftc"> <head> <script src="/assets/2db3448a/components/angular.js/angular.min.js">&l ...

Refresh choices for the user interface selection menu

I've successfully mastered the art of redefining options for Webix ui.richselect/ui.combo. The technique involves: richselect.getList().clearAll(); richselect.getList().parse(options_data) Now, I'm facing a challenge with changing options fo ...

Warning: Potential critical dependency detected while utilizing react-pdf package

When attempting to showcase a PDF on my react application, I encountered the following warning: /node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js Critical dependency: require function is used in a way in which dependencies cannot be static ...

Accessing data returned from JSON in JQuery beyond the code block required

Is there a way to access returned JSON data outside of the JQuery getJSON method? For example: var price = ""; $.getJSON("../JSONDeliveryPrice", null, function (data) { price = eval(data.price); }); console.log(price); Unfortunately, this code does not ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Finding the Nearest Value in an Array

My code involves a changing total number that I need to match with the closest value in an array of numbers, returning the index of the matching person, which should be Mia Vobos. I am attempting to find two people whose scores add up to the same total or ...

Is the MVC pattern adhered to by ExpressJS?

Currently, I am diving into the world of creating an MVC Website With ExpressJS using resources from I'm curious to know if ExpressJS strictly adheres to the MVC pattern, or if it follows a different approach like Flask which focuses more on the "C" ...

Component binding causing issues with onChanges functionality

There is a specific component that I am working on: @Component('Umbrella', { selector: 'attachment-list', templateUrl: '/AttachmentListComponent/AttachmentList.html', bindings: { mediaIds: '<' ...

Troubleshooting problem with the oninput function of a custom JavaScript element

Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js file: class Oninput ...

Launching an AngularJS project: seeding versus scripting

I am currently in the process of developing a small AngularJS application for deployment on a web server, but I am struggling to grasp the difference between utilizing Angular's startup seed as opposed to directly linking the script in the HTML, such ...

Is there a way to transfer the submitted data to a different page without being redirected to it using #php and #ajaxjquery?

Hey there, I could use a little assistance. How can I send data to page update.page.php when submitting a form on index.php without being redirected? I want the functionality of sending a message from one page to another without having to refresh the ent ...

AngularJS: Retrieve country, state, and city data from a database for selection

I am looking to implement a country, state, and city selection feature on my website. I already have separate tables for countries, states, and cities in my database. City Table CREATE TABLE IF NOT EXISTS `cities` ( `city_id` int(11) NOT NULL, `city_ ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...