[英]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
.您可以使用正则表达式来替换不在
az
或AZ
或0-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.