Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing numbers and characters from a string

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!

like image 308
Modelesq Avatar asked Jan 09 '13 21:01

Modelesq


People also ask

How do I remove a specific number of characters in a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove all characters from a string except numbers?

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.


1 Answers

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

like image 183
jahroy Avatar answered Sep 22 '22 23:09

jahroy