5

If a user clicks on a tag, right now it recognizes the full text (numbers and characters).

returns Popular Tag %82

I've tried:

$tag.click(function(){
  var $this = $(this);
  var text = $this.text();
  var num = text.parseInt();
  num.remove();
  alert(text)
});

Doesn't do the trick for numbers. So how would I get just the letters? Ie: ignoring BOTH numbers and special characters(%)

Fiddle here! Thanks for you help!

jahroy
  • 22,322
  • 9
  • 59
  • 108
Modelesq
  • 5,192
  • 20
  • 61
  • 88

2 Answers2

18

The simplest way is to use a regex:

var s = "ABCblahFoo$%^3l";
var letters = s.replace(/[^A-Za-z]+/g, '');
  • the [] represents a character (or a number of different possible characters)
  • the ^ means all characters EXCEPT the ones defined in the brackets
  • A-Z equals capital letters
  • a-z equals lowercase letters

So... Replace every character that is NOT a letter with the empty string.

jsFiddle Demo

jahroy
  • 22,322
  • 9
  • 59
  • 108
  • 2
    +1, but I would add a `+` to the `[^A-Za-z]` so that if there are consecutive characters to be removed, they can be can be removed in one go, as opposed to one by one. – zx81 May 24 '14 at 03:00
  • @jahroy You're welcome, after seeing you on the other regex question I enjoyed a cruise through some of your answers. :) – zx81 May 24 '14 at 03:26
  • @zx81 - Likewise. I've enjoyed that [other question](http://stackoverflow.com/questions/23839481/find-out-the-position-where-a-regular-expression-failed) as well (though I'm out of my league) and hope the dialogue continues some more! – jahroy May 24 '14 at 04:42
  • @jahroy He does sound quite competent and I too would like to hear from him—the convo could be interesting and I'm sure I'd learn something. Nice being in touch, wishing you a relaxing weekend. – zx81 May 24 '14 at 05:12
0

the above answer will remove spaces from the string.

var str = "Hello^# World/";
str.replace(/[^a-zA-Z ]/g, "");

use this. Simply add space after A-Z in the regex.

Buddhika Lakmal
  • 155
  • 1
  • 3