1

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.

3
  • What type of element has the .TwitterSpot class? Commented Feb 3, 2012 at 15:20
  • jsfiddle.net/2xHnt -- Works fine for me. Commented Feb 3, 2012 at 15:21
  • Are you wanting to do this server side or client side? Commented Feb 3, 2012 at 15:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This needs to also grab the text value of the tag so that it can be added to the url.
Is there a way of not losing formatting for other elements within .TwitterSpot div?
@Anicho: there are more elements contained by that div? Uhh that would get a little more tricky then. We would need to get the .contents() from the element and find the TextNode to modify.
No issue you got me going in the right direction /#/g worked like a charm. I'll target the element directly within .TwitterSpot instead.
2

.replace takes a regular expression. To replace all you have to use the global ("g") flag.

.replace(/#/g, 'Blah Blah')

4 Comments

This needs to also grab the text value of the tag so that it can be added to the url
Is there a way of not losing formatting for other elements within .TwitterSpot div?
@pete the type may be string, but it's understood as a regular expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.