Trouble capitalizing first word in input with javascript/jquery

前端 未结 2 783
旧巷少年郎
旧巷少年郎 2021-01-27 08:49

I have looked through a lot of the other threads on here with this question. I am having issues capitalizing the first letter of an input.

http://jsfiddle.net/sA9c8/2/

相关标签:
2条回答
  • 2021-01-27 09:06

    Are you trying to do this

    function crmForm_lastname_onblur(sourceField, sourceRowId) {
        var val = sourceField.value;
    
        if (val.charAt(0).toUpperCase() != val.charAt(0)) 
             sourceField.value = val.charAt(0).toUpperCase() + val.slice(1)
    }
    

    FIDDLE

    0 讨论(0)
  • 2021-01-27 09:10

    Given that your Regex is only matching the first letter after a word boundary, your replacement function should be:

    x.value = x.value.toLowerCase().replace(/\b[a-z]/g, function (letter) {
        return letter.toUpperCase();
    });
    

    to capitalize the first letter of each word (demo).

    If you only want the very first letter in the input captialized, change your Regex and keep the same replacement function above:

    x.value = x.value.toLowerCase().replace(/^[^A-Za-z]*\b[a-z]/, function (letter) {
        return letter.toUpperCase();
    });
    

    /^[^A-Za-z]*\b[a-z]/ captures the first letter of the input (demo).

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