I have an array with Twitter hashtags. And I want to filter a string tw.text
for those hashtags and wrap the words in a span
var hashtags = new Array("home","car", "tree");
tw.text.replace('#home', '<span class="hash">#home</span>')
How would I do that?
Thank you in advance.
The . splice() method lets you replace multiple elements in an array with one, two, or however many elements you like.
Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.
If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
Given a string and a pattern, replace multiple occurrences of a pattern by character 'X'.
hashtags.forEach(function (elem) {
tw.text = tw.text.replace('#' + elem, '<span class="hash">#' + elem + "</span>");
});
This does not account for tags that contain other tags which could lead to duplicate replacement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With