Javascript to remove spaces from a textbox value

扶醉桌前 提交于 2019-11-29 04:37:58

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

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".

Here is a function I use to replace spaces.

function removeSpaces(val) {
   return val.split(' ').join('');
}

Another, more jQuery'ish option:

$(".stripspaces").keyup(function() {
    $(this).val($(this).val().replace(/\s/g, ""));
});

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>

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>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!