Javascript to remove spaces from a textbox value

后端 未结 7 1366
一生所求
一生所求 2020-12-17 00:44

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 bo

相关标签:
7条回答
  • 2020-12-17 00:47

    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);
    
    0 讨论(0)
  • 2020-12-17 00:48

    Another, more jQuery'ish option:

    $(".stripspaces").keyup(function() {
        $(this).val($(this).val().replace(/\s/g, ""));
    });
    
    0 讨论(0)
  • 2020-12-17 00:52

    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>
    
    0 讨论(0)
  • 2020-12-17 00:59

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

    0 讨论(0)
  • 2020-12-17 01:00

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

    0 讨论(0)
  • 2020-12-17 01:01

    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>

    0 讨论(0)
提交回复
热议问题