12

I've searched around for this a lot and can't find a specific example of what I'm trying to do. Basically I want to get the value of a textbox, by the name of the text box (not id). Then I want to remove ALL spaces, not just leading or trailing, but spaces in the text too. For example for this html code:

<INPUT style="TEXT-ALIGN: right;" onkeyup="fieldEdit();" onchange="fieldChange();" NAME="10010input" VALUE="4 376,73" readonly >

I have this javascript:

var val = document.CashSheet.elements["10010input"].value; 
val2 = val.replace(<someregex>, '');
alert(val2);

But I've tried many available regex expressions that remove all spaces, but all only seem to remove leading and trailing spaces, for example the value above 4 376,73 should read as 4376,73 in the alert above but it doesn't. After looking into this normal regex for removing spacesfrom a text field contents is not working and I believe its because its being populated in Polish localised settings on the web server. What \u char/regex exp do I need to capture for a "Polish space" so to speak, in ascii it comes up as 20 but the regex exps that most people are suggesting for spaces does not capture it.

TMS
  • 143
  • 1
  • 1
  • 7

7 Answers7

16

You can use document.getElementsByName to get hold of the element without needing to go through the form, so long as no other element in the page has the same name. To replace all the spaces, just use a regular expression with the global flag set in the element value's replace() method:

var el = document.getElementsByName("10010input")[0];
var val = el.value.replace(/\s/g, "");
alert(val);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Hi Tim, quick question, I am trying what you're suggesting for a text field contents but its not working and I believe its because its being populated in Polish localised settings on the web server. What \u char do I need to capture for a "Polish space" so to speak, in ascii it comes up as 20 but the regex does not capture it, but will capture other spaces I put in a string myself. – TMS Oct 19 '10 at 08:20
  • Really? Are you sure that's not 20 in hex (the normal space character is 20 in hex)? If you need to specify a list of space characters to match you could do something like `new RegExp("[\\s\u1234\u4321]", "g")` instead of `/\s/`. – Tim Down Oct 19 '10 at 09:22
  • Yep, its coming back like "4 376", if I try that regex on it, it doesn't do anything but if i add "a a" to the end of that string the regex will make it output like this: "4 376aa" so it works on my space but not on the space coming back from the Polish web server. I think its a different Unicode space character, which I will try to find which one it is then use you new RegExp call. – TMS Oct 19 '10 at 09:52
  • Ok i found its \u00A0 , so a nbsp, but need to find a regex that matches that now as new RegExp("[\\s\u00A0]", "g") doesn't work :( – TMS Oct 19 '10 at 14:04
  • Really? `new RegExp("[\\s\u00A0]", "g").test("\u00A0");` works for me, including in IE (in which `\s` doesn't match `\u00A0`, violating the ECMAScritp spec). – Tim Down Oct 19 '10 at 14:24
  • This did it! .replace([\f\n\r\t\v\u00A0\u2028\u2029], '_') – TMS Oct 19 '10 at 14:34
6

You need to "generalize" that regexp you're using so it's applied to all matches instead of just the first. Like this:

val = val.replace(/\s/g, '')

Notice the 'g' that modifies the regexp so it becomes "general".

Abel Tamayo
  • 165
  • 1
  • 7
  • 2
    +1 for `\s` character class; I'd probably use the work "global" instead of "general" – Michael Haren Oct 18 '10 at 15:39
  • 1
    @Michael: Why is `\s` significantly better than just a space character here? There can't be any line break characters in an `` and non-breaking spaces are not commonly typed into a text box. – Tim Down Oct 18 '10 at 15:45
  • @Michael Haren: I knew it started with a 'g', but I didn't know which one it was exactly. @Tim Down: I think \s is more readable, isn't it? – Abel Tamayo Oct 18 '10 at 16:54
  • @Abel: Dunno. Quite subjective, I'd say. It's not a big issue, and `\s` is probably the better option functionality-wise. – Tim Down Oct 18 '10 at 19:26
  • @Tim There are dozens of whitespace characters that could be pasted in that aren't a simple "space" – Michael Haren Oct 18 '10 at 22:39
  • @Michael: Not many are covered by `\s` though. It matches precisely nine characters (\u0009, \u000A, \u000B, \u000C, \u000D, \u0020, \u00A0, \u2028 and \u2029). However, I concede the point: `\s` is the better option. – Tim Down Oct 18 '10 at 23:55
  • Hi all thanks for the replies, quick question at Tims comment, I am trying what you're suggesting for a text field contents but its not working and I believe its because its being populated in Polish localised settings on the web server. What \u char do I need to capture for a "Polish space" so to speak, in ascii it comes up as 20 but the regex does not capture it, but will capture other spaces I put in a string myself. – TMS Oct 19 '10 at 08:20
  • Some browsers do allow pasting CR/LF into in `` elements. – eyelidlessness Oct 19 '10 at 08:26
  • @eyelidlessness: Yes. My phrasing was bad in an attempt to keep things simple. – Tim Down Oct 19 '10 at 09:18
6

Here is a function I use to replace spaces.

function removeSpaces(val) {
   return val.split(' ').join('');
}
James Lawruk
  • 30,112
  • 19
  • 130
  • 137
4

Another, more jQuery'ish option:

$(".stripspaces").keyup(function() {
    $(this).val($(this).val().replace(/\s/g, ""));
});
yglodt
  • 13,807
  • 14
  • 91
  • 127
  • 2
    Too much jQuery... [When to use Vanilla JavaScript vs. jQuery?](http://stackoverflow.com/questions/4651923/when-to-use-vanilla-javascript-vs-jquery). Besides, all answers at this page have a major flaw: By always setting the value, the caret always moves to the end, even if there's no space in the box. A better solution would involve checking the input's value first. – Rob W Feb 06 '13 at 15:38
3

Try this: you can try to write or copy paste any string including white space, it's removed automatically.

/* Not Allow Spcace Type in textbox */
function AvoidSpace(event) {
    var k = event ? event.which : window.event.keyCode;
    if (k == 32) return false;
}

/* Remove Blank Space Automatically Before, After & middle of String */

function removeSpaces(string) {
 return string.split(' ').join('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
<input placeholder="Enter Your Text" type="text" onkeypress="return AvoidSpace(event);" onblur="this.value=removeSpaces(this.value);">


</form>
halfer
  • 19,824
  • 17
  • 99
  • 186
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36
2

Try This

<script language="JavaScript">
function RWS(str){
  return str.replace(/^\s+/,"").replace(/\s+$/,"").replace(/\s+/g," ");
}
</script>

<form name=f1ex>
<textarea name="t2" rows="5" onChange="this.value=RWS(this.value)"></textarea>
</form>
Muddasir Abbas
  • 1,699
  • 1
  • 20
  • 37
0

you can use this jQuery method http://api.jquery.com/jQuery.trim/
val = $.trim(val); OR val = jQuery.trim(val);

Amr Badawy
  • 7,453
  • 12
  • 49
  • 84
  • This only removes leading and trailing spaces and not Polish Unicode spaces inside a string :( – TMS Oct 19 '10 at 08:48