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

What could be causing my "onChange" function to not work as expected?

export function UpdateData(props){ return( <div> <div className='updateForm'> <form> <div className="form-group"> <label>Your ID:& ...

Tips for modifying the content displayed on a v-list in Vue.js dynamically

I am looking to create a dynamic list that displays data based on the selected key. The list will contain multiple items with different keys, and I want the flexibility to choose which data to display without hardcoding the actual key value. <template&g ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...

What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable. function saveSelection() { console.log('inside function') var postToDatabase = []; vm.newApplicant.values ...

Retrieve the tweets from the next Twitter user in the Array using blogger.js

I am working on a project that involves a javascript array of Twitter usernames. Using blogger.js, I successfully load the first username along with their last 5 tweets. Now, I am looking to create HTML buttons or links for "previous" and "next" in order ...

How can I apply angular ng-repeat filter with specific criteria in mind?

I am currently developing an angular application and I need to present customer data in a table using ng-repeat. While I have successfully added ng-filter for searching the results based on user input, I am now looking to incorporate checkboxes to further ...

Exploring the concept of Promises through the lens of recursion

I am dealing with a MongoDB collection that looks like this [ { "classId": "1", "name": "Input", "definition": [ { "property": [ { "classId": "12", "name": "One" }, { ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Will my JavaScript function be triggered when the page is resized while printing?

I have a simple HTML layout where I am using the TextFill jQuery library to automatically adjust the text size based on available space. Everything looks good on screen, but when printed, it seems like the page is resized and the JavaScript needs to be re ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Is it possible to execute PHP without using Ajax when clicking on a Font Awesome icon?

So, besides using Ajax, is there another solution to achieve the same result? Can a font-awesome icon be turned into a button without Ajax? In case you're unfamiliar with what I mean by a font-awesome icon, here's an example: <i id="like1" on ...

Using ngFor and ngModel: What is the best way to add values to the beginning of the array I am looping through?

I am facing an issue with my array of elements in which users can edit, add, and delete complete array elements. Everything works smoothly until I try to add a value to the beginning of the array using the unshift method. Below is a test that showcases th ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...

What is the best way to separate a table column into a distinct column at the specified delimiter count?

I successfully wrote code that splits the third column into new columns at the slash delimiter. However, I am struggling to modify it to split at the nth (i.e. 2nd) occurrence. I couldn't find a solution online, so I'm reaching out here for help ...

Tips for implementing an onclick jquery function within an input field

Just starting out with JavaScript and jQuery, I have a jQuery function that looks like this: $('.input-group .date').datepicker({ }); I want to apply it to the following HTML structure: <div class="input-group date" id="dp3"> <inp ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...