最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Replacing alpha characters and spaces in string with jQuery - Stack Overflow

matteradmin2PV0评论

I have a string that allows only numbers

$(this).val($(this).val().replace(/([a-zA-Z])/g, ""));

How can I add a space, so this will get replaced with "" same way in one string?

I have a string that allows only numbers

$(this).val($(this).val().replace(/([a-zA-Z])/g, ""));

How can I add a space, so this will get replaced with "" same way in one string?

Share edited Sep 25, 2013 at 8:59 xec 18k3 gold badges47 silver badges58 bronze badges asked Sep 25, 2013 at 8:34 DomDom 3,12614 gold badges48 silver badges69 bronze badges 3
  • try this... stackoverflow./questions/181356/… – asharajay Commented Sep 25, 2013 at 8:37
  • where do you want to add space exactly? – Mehmed Commented Sep 25, 2013 at 8:38
  • possible duplicate of How to allow only numeric (0-9) in HTML inputbox using jQuery? – Ram Commented Sep 25, 2013 at 8:38
Add a ment  | 

3 Answers 3

Reset to default 7

To match only non-numerics, you would do [^0-9] instead of [a-zA-Z] (this is called a negated character class).

If you want an input to allow only numbers, with HTML5 you can simply do <input type="number">. For wider support, there are plenty of JavaScript solutions, have a look at How to allow only numeric (0-9) in HTML inputbox using jQuery? as suggested in the ments.

Just add the space to your Regex:

  "asfasd asdf asdf".replace(/([a-zA-Z ])/g, "");

Yields:

  ""

Edit: I misunderstood your question. If you want to prevent every input but numbers use this regex:

function removeNotAllowedChars($input) {
   $input.val($input.val().replace(/[^0-9]/g, ''));
}

$('#myText')
   .keyup(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   })
   .change(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   });

Using these script removes the input instantly if the user types the character and if he pastes the input after the focus changes. Try it here: JSFiddle

use \s - Matches a single white space character, including space, tab, form feed, line feed. Equivalent to

Regex Guide

Post a comment

comment list (0)

  1. No comments so far