简体   繁体   English

如何使用javascript或jquery删除/删除单词的第一个空格?

[英]How to remove/delete first space of word using javascript or jquery?

I want to remove first space from text field. 我想从文本字段中删除第一个空格。 i have created function which allow only characters. 我创建了仅允许字符的功能。 Here is my html code : 这是我的html代码:

<form:input path="deliveryBoyName" id="deliveryBoyName"
        maxlength="100" class="form-control" 
       onkeypress="return onlyAlphabets(event,this);">
</form:input>

Here is my javascript function : function onlyAlphabets(e, t) { 这是我的javascript函数:only functionAlphabets(e,t){

try {
    if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }
    if (charCode == 0 || charCode == 8 || charCode == 17 || charCode == 20 || charCode == 32 || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
        return true;
    else
        return false;
}
catch (err) {
    alert(err.Description);
} }

Now if user first types space then it should remove. 现在,如果用户首先键入空格,则应将其删除。 starts only from character. 仅从字符开始。

For example : 
If user types like " Hello World" 
Then it should not allowed. 
If user type like "Hello World" then its should allowed. please help me.    
Thank you in advance.

JavaScript trim() function can remove white spaces from both the side. JavaScript trim()函数可以从两侧去除空格。

Here is working fiddle - 这是工作提琴-

 var str = " Did you find solution Ashish? If yes then tick it."; alert(str.trim()); 

I think you want to allow space only when it is not the first character. 我认为您只想在不是第一个字符时才允许空格。

This is what you want, ie your function removing all the unnecessary code: 这就是您想要的,即您的函数删除了所有不必要的代码:

function onlyAlphabets(e, t) {
  var charCode = e ? e.which : window.event.keyCode;

  return (charCode == 0  || charCode == 8  || charCode == 17 || charCode == 20 ||
          (t.value.length && charCode == 32) || 
          (charCode > 64 && charCode < 91) || 
          (charCode > 96 && charCode < 123))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM