TIMEX
TIMEX

Reputation: 271844

In JQuery, how do I remove a comma after removing an element?

var body = 'Alex, <a href="blah" title="jason">Jason</a>, Kate, how are you?";

I want to use JQuery to remove the anchor element from body, and then also remove the comma after the anchor, if there is any. Note: to make it easy, the comma will always be after the anchor with no other characters in between.

Upvotes: 0

Views: 311

Answers (2)

Alnitak
Alnitak

Reputation: 339816

I'm assuming (to maintain grammatical consistency) that you also want to remove the contents of the anchor.

Firstly, use a regexp to get rid of the comma:

var body = 'Alex, <a href="blah" title="jason">Jason</a>, Kate, how are you?';
body = body.replace(/(<\/a>),/g, '$1')

Then to allow jQuery to work on the string you need to enclose it in an element:

body = '<div>' + body + '</div>'

Then you can actually remove the element

body = $(body).children('a').remove().end().html();

NB: the code above will remove all <a> elements within the text, but leave other HTML elements therein untouched.

Upvotes: 1

Thomas Clayson
Thomas Clayson

Reputation: 29925

If you're thinking of removing elements like that then it would be better to encase them in something to "mark them off" as it were. You're saying that the name "Jason" is tied to the superseding comma, so mark them off. e.g.:

var body = 'Alex, <span class="name"><a href="blah" title="jason">Jason</a>,</span> Kate, how are you?";

Then to remove in jquery you can do something like:

$('a').click(function(){ $(this).closest('.name').remove(); });

This is the best way to do it, mainly because you have control over what is important to which text elements. A regex, or some way of removing the next single character will work in your example, however what happens if you want to extend your sentence, eg: 'Alex, <a href="blah" title="jason">Jason</a> (the farmer's son), Kate, how are you?'.

Upvotes: 0

Related Questions