Jquery Trim all spaces from variable

放肆的年华 提交于 2020-05-17 07:08:45

问题


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!


回答1:


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




回答2:


Use it like this:

var str = songToTrim.trim().replace(/\s+/g, ' ');
var lower = str.toLowerCase();


来源:https://stackoverflow.com/questions/27415631/jquery-trim-all-spaces-from-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!