Remove comma with jQuery

4

I have a part of a blog that is manageable.

These are the TAGS. By default in the system, you tell the TAG in a specific field and it includes the blog.

The code looks like this:

<a href='blablabla' class='tags'>tagSYS, </a>

That is, tagSYS is the reserved word, what happens is that it always includes a comma, this is correct when it has more than one word.

But when you have only one, or when it's the last word, it's strange a "," where there is no continuation.

Can you take this with jQuery?

I thought about using $( "tags" ).last()... I do not know the syntax for removing 'text'.

An example:

    
asked by anonymous 23.05.2014 / 13:57

2 answers

6

Example: link

Option A

You can use a regular expression to take only the last comma. I've also put together another replace to clean up blanks.

var string = $('.tags').text();
string = string.replace(' ','').replace(/,+$/, "");

The $ selector in regular expressions indicates end of string.

Option B

You can also just remove the last character from the string like this:

var string = $('.tags').text();
string = string.replace(' ','');              // limpar espaços em branco
string = string.substr(0, string.length - 1); // usar todos os caracters até ao penúltimo

Note that this option removes any last character. Not just a comma.

EDIT: I noticed in the comments below that each tag has its element <a> in this case you have to use the pseudo-selector :last or .last() as you suggested in the question (and I did not give you any attention) p>

So you can pass a function to .html() of jQuery and do:

$('.tags:last').html(function () {
    var string = $(this).text();
    string = string.replace(' ', '').replace(/,+$/, "");
    $(this).text(string)
});

Example: link

    
23.05.2014 / 14:05
3
var noCommas = $('.tags').text().replace(/,/g, ''),
    asANumber = +noCommas;

Just use replace

If you want to check the last character, follow the full function:

if (campo.substring(campo.length-1) == ",")
{
    replace
}
    
23.05.2014 / 13:59