Remove comma with jQuery

Asked

Viewed 6,247 times

4

I have a part of a blog that is manageable.

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

The code is like this:

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

That is, the 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 there is only one, or when it is the last word, it is strange a "," where there is no continuation.

You can take it off with jQuery?

I thought I’d use $( "tags" ).last()... I don’t know the syntax to remove 'text'.

An example: inserir a descrição da imagem aqui

  • I believe that you should correct this generation, not add a comma to the last element

  • @Erloncharles is exactly what I’m trying to do...

2 answers

6


Example: http://jsfiddle.net/DCeU6/

Option A

You can use a regular expression to take out only the last comma. I also added another replace to clear whitespace.

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

The selector $in regular expressions indicates end of string.

Option B

You can also simply 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 only a comma.


EDIT: Notice in the comments below that each tag has its element <a> then you must use the pseudo-selector :last or the .last() as you suggested in the question (and I gave no homage)

So you can pass a function to the .html() jQuery and make:

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

Example: http://jsfiddle.net/DCeU6/5/

  • Your example worked perfectly. But for me, not yet, here’s an example: http://jsfiddle.net/felipestoker/ekth9/

  • 1

    @Felipestoker, http://jsfiddle.net/ekth9/1/

  • Thank you very much, it worked! D

3

var noCommas = $('.tags').text().replace(/,/g, ''),
    asANumber = +noCommas;

Just use the function replace

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

if (campo.substring(campo.length-1) == ",")
{
    replace
}
  • Thank you. But with that, he will identify which is the last element?

  • 1

    Please check the Edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.