Reputation: 1515
I am trying to filter out the hashtags in a text string, by splitting it, and removing unwanted HTML tags.
I'm not getting the correct output, and I am not too sure where I am making my mistake, and would appreciate your guidance.
This is an example of the text string value:
"<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 I have thus 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);
My desired output is: #fnb, #mobilesimcard, #what, #refugeechild
My str.split()
is not working correctly, and I believe I will have to expand on the .replace()
as well.
Thank you!
Upvotes: 0
Views: 2387
Reputation: 27202
Try array map() method :
Working demo :
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);
Upvotes: 1
Reputation: 3268
A solution with a regular expression:
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 regex is just a very simple one, there are tons better in the wild, like Best HashTag Regex
Upvotes: 2