简体   繁体   中英

Javascript - I can't concatenate at the beginning of my string

Here's what I want to do:

Check if there is the first character "@" within my string, If not, add it.

Here is my code:

$(document).ready(function(){

    $("#twitter").blur(function() {
            var s = $("#twitter").val();
            alert(s);
            var isAt = s.charAt(0);
            alert(isAt);
            if(isAt !== "@") {
                alert("lol");
                s = "@" + s;
            }
        });
});

The Problem:

When I tab to the next input (in turn blurring #twitter) Its lol'ing but not setting the value of the input to "@Rick" when I type "Rick".

Any ideas why?

Change this:

s = "@" + s;

to this:

$("#twitter").val('@' + s);

The problem is that you're updating the value stored in your s reference, but there's no dynamic binding between that variable and the input field itself (ie, you have to still update the #twitter value manually).


Edit: as suggested by @epascarello below, this is probably a cleaner solution:

$(document).ready(function(){
    $('#twitter').blur(function() {
        var $this = $(this),
            val = $this.val();
        if (val.charAt(0) !== '@') {
            $this.val('@' + val);
        }
    });
});

And... just for the heck of it, another approach:

$(document).ready(function(){
    $('#twitter').blur(function() {
        if (this.value.charAt(0) === '@') return;
        $(this).val(function(i, v) { return '@' + v });
    });
});

One more...

$(document).on('blur', '#twitter', function() {
    $(this).val(function(i, v) {
        return v.replace(/(@)?(.*)/, '@$2')
    });
});

Note: you should probably use the first or second one... i'm getting esoteric over here...

$(document).ready(function(){
    $("#twitter").blur(function() {
        var s = $("#twitter").val();
        alert(s);
        var isAt = s.charAt(0);
        alert(isAt);
        if(isAt !== "@") {
            alert("lol");
            $("#twitter").val("@" + s);
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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