Jquery Trim all spaces from variable

2019-08-24 16:36发布

On a click I store a variable. I would like to then trim that variable for all whitespace. I am getting an error when I to simply console.log the new variable.

var songToTrim = $(this).html();
console.log(songToTrim);
var songToPlay = songToTrim.replace(/ /g,'');
console.log(songToPlay);

For bonus points if you can add how to make sure the variable is converted to all lowercase that would be huge. If not it'll still work. Thanks!

2条回答
成全新的幸福
2楼-- · 2019-08-24 17:14

Here is my solution

Code:

 $("#test").on('click', function(){
    var songToTrim = $(this).html();
   var trm  = songToTrim.replace(/ /g,'');
   var songToPlay = trm.toLowerCase();
    });

Use .toLowerCase() to convert your variable to Lower Case.

The error you are getting is because you have a typo in your code somewhere. You have misspelled Console as Consle.

Find it and correct it.

Here is a working Demo

查看更多
够拽才男人
3楼-- · 2019-08-24 17:24

Use it like this:

var str = songToTrim.trim().replace(/\s+/g, ' ');
var lower = str.toLowerCase();
查看更多
登录 后发表回答