Turn string to uppercase before dash

Asked

Viewed 141 times

1

How to capitalize string before a dash ( - ) as typed, using jQuery/Javascript?

Text example: "ab-Hello world Cx- All right?"

Exit: AB- Olá mundo CX- Tudo bem?

//
$('textarea').keyup(function(){
   $(this).val( ? );
});
  • how to mark the status of this post as SOLVED?

2 answers

2

You can do it like this:

$('textarea').keyup(function(){
   var mystr = $(this).val();
   var myarr = mystr.split("-");
   var myvar = myarr[0].toUpperCase() + "-" + myarr[1];
});

Using the split to separate the values and the toUpperCase to be converted into an uppercase.

Remembering that this solution was made for a single -

  • It wouldn’t be right to access the array by the beginning 0? myarr[0].toUpperCase(). What happens if he has multiple strokes -?

  • really @gabrielhof didn’t think about the chance to have you more than one - and the indices are correct

  • Take a look at what happens: http://jsfiddle.net/qbbgx3e7/

  • 1

    yes @gabrielhof already edited the answer adjusting the array and tested together in your fiddle worked

0

Solved

function beforeDash( val ){
    return val.replace(/(?:\w+-)/g, function(match){
        return match.toUpperCase()
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.