用于从文本框值中删除空格的Javascript [英] Javascript to remove spaces from a textbox value

查看:201
本文介绍了用于从文本框值中删除空格的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常搜索这个,但找不到我想要做的具体例子。基本上我想通过文本框的名称(而不是id)获取文本框的值。然后我想删除所有空格,不仅仅是前导或尾随,还要删除文本中的空格。例如,这个html代码:

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 >

我有这个javascript:

I have this javascript:

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

但我尝试了许多可用的正则表达式删除所有空格,但似乎只是删除了领先和尾随空格,例如4 376,73以上的值应该在上面的警告中读作4376,73,但事实并非如此。在查看这个正常的正则表达式以从文本字段中删除空格后,内容不起作用,我相信它,因为它在Web服务器上的波兰语本地化设置中填充。什么\u char / regex exp我需要捕获一个波兰空间可以这么说,在ascii它出现为20但正则表达式,大多数人建议空间不捕获它。

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.

推荐答案

您可以使用 document.getElementsByName 来获取元素而无需去通过表单,只要页面中没有其他元素具有相同的名称。要替换所有空格,只需使用正则表达式,并在元素值的 replace()方法中设置全局标志:

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);

这篇关于用于从文本框值中删除空格的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆