Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Text Replace for multiple strings in array?

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.

like image 221
matt Avatar asked Mar 10 '13 18:03

matt


People also ask

How do you replace multiple elements in an array?

The . splice() method lets you replace multiple elements in an array with one, two, or however many elements you like.

How do I replace multiples in a string?

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.

How can I replace multiple characters in a string using jquery?

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.

Which one is correct string function replace multiple occurrences in input string?

Given a string and a pattern, replace multiple occurrences of a pattern by character 'X'.


1 Answers

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.

like image 126
Explosion Pills Avatar answered Oct 19 '22 09:10

Explosion Pills