2016-02-20 69 views
1

我想從文本字段中刪除第一個空格。我創建了只允許字符的函數。 這裏是我的html代碼:如何使用javascript或jquery刪除/刪除第一個空格的單詞?

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

這裏是我的javascript函數: 功能onlyAlphabets(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); 
} } 

現在,如果用戶第一類型的空間,那麼就應該刪除。只從字符開始。

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. 

回答

1

我想你想只允許空間時,它不是第一個字符。

這是你想要的,即你的功能刪除所有不必要的代碼:

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)) 
} 
3

JavaScript trim()函數可以從兩側刪除空白。

這裏是工作提琴 -

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

+0

它不會在我的情況下工作。因爲我只想移除第一個空間。應該允許使用兩個詞的空格。 @kalpeshSIngh –

+0

它不會刪除兩個單詞之間的空格。它將從開始和結束時刪除。 :) –

+0

感謝它的作品。 @KalpeshSingh –

相關問題