简体   繁体   中英

How to remove everything from string after the last character?

I am practicing and I wrote length of last word in JS.

var lengthOfLastWord = function (s) {
    var words = s.split(" ");
    var len = words.length;
    for (let i = 0; i < len; i++) {
        if (len == 1){
            var last_element = words[0];
        }
        else {
            var last_element = words[len - 1];
        }
    return last_element.length;    
    }
}

But it doesn't work well if

s = 'a ' 

or

s = 'Hello.'

How to write substring to remove everything except characters?

You can use regex to replace charachters those are not in az or AZ or 0-9 . or simply just use \\W in regex expression :

   var last_element = words[len - 1].replace(/\W/g, "");

I would suggest you to try the following code:

s = 'Hello. '
s.trim();

The trim() function removes all whitespaces from your String.

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