I have the following:
var newValue = $('.TwitterSpot').text().replace('#', 'Blah Blah');
$('.TwitterSpot').text(newValue);
My assumption is that it will get all characters or pieces of text that have "#" replace it with Blah Blah.
It is not working? What am I missing?
The end result I want is to get #tag and replace it with a link to a link to twitter.com/#!/search/%23tag.
2 Answers 2
I'd suggest to do it like
$('.TwitterSpot').text(function(_, text) {
return text.replace(/#/g, 'Blah Blah');
});
.text() like many other getter/setter jQuery functions offers a callback which gets passed in the current value. By returning a new value you can update that string.
Your mistake was not using a regular expression for the .replace() function. By doing that you can set the global flag g, which makes sure every occurence is matched.
4 Comments
.contents() from the element and find the TextNode to modify..replace takes a regular expression. To replace all you have to use the global ("g") flag.
.replace(/#/g, 'Blah Blah')
.TwitterSpotclass?