简体   繁体   English

如何从最后一个字符后的字符串中删除所有内容?

[英]How to remove everything from string after the last character?

I am practicing and I wrote length of last word in JS.我正在练习,我在 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 .您可以使用正则表达式来替换不在azAZ0-9 or simply just use \\W in regex expression :或者只是在正则表达式中使用\\W

   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. trim()函数从您的字符串中删除所有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JS 删除最后一次出现字符后的所有内容 - JS remove everything after the last occurrence of a character 字符串 删除最后一个连字符后的所有内容 - String Remove Everything after Last Hyphen 如何从While循环中的最后一个字符串中删除最后一个字符? - How to remove the last character from last string in a While loop? 如何删除特定字符后的所有内容 - How to remove everything after particular character 在最后一次出现特定字符后,如何删除字符串的特定部分? - How to remove a specific section of a string after the last occurrence of a specific character? 如何删除字符串中最后一个逗号字符后的所有内容? - How to remove every thing after last comma character in a string? 如何从 javascript 中的字符串数组中删除特定字符串之后的所有内容 - how to remove everything after a particular string from an array of strings in javascript 如何从字符串中删除符号以及此符号之后的所有内容 - How to remove symbol and everything after this symbol from a string 删除字符串中某个字符之后的所有内容,但保留在标签中 - Remove everything after a certain character in a string but keep wrapped in tag 使用JavaScript删除字符串中某些字符之后的所有内容 - Remove Everything After Certain Character Within String Using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM