[英]Remove all characters after the last special character javascript
I have the following string.我有以下字符串。
var string = "Welcome, to, this, site";
I would like to remove all characters after the last comma, so that the string becomes我想删除最后一个逗号后的所有字符,使字符串变为
var string = "Welcome, to, this";
How do I go about it in Javascript?我如何在 Javascript 中处理它? I have tried,我努力了,
var string = "Welcome, to, this, site";
string = s.substring(0, string.indexOf(','));
but this removes all characters after the first comma.但这会删除第一个逗号后的所有字符。
你需要的是lastIndexOf:
string = s.substring(0, string.lastIndexOf('?'));
you can use split and splice to achieve the result as below.您可以使用 split 和 splice 来实现如下结果。
var string = "Welcome, to, this, site";
string = string.split(',')
string.splice(-1) //Take out the last element of array
var output = string.join(',')
console.log(output) //"welcome, to, this"
There's a String.prototype.lastIndexOf(substring)
method, you can just use that in replacement of String.prototype.indexOf(substring)
:有一个String.prototype.lastIndexOf(substring)
方法,你可以用它来代替String.prototype.indexOf(substring)
:
var delimiter = ",";
if (inputString.includes(delimiter)) {
result = inputString.substring(0, inputString.lastIndexOf(delimiter));
} else {
result = inputString;
}
Alternatives would include Madara Uchiha 's suggestion :替代方案包括Madara Uchiha的建议:
var delimiter = ",";
var parts = inputString.split(delimiter);
if(parts.length > 0) { parts.pop(); }
result = parts.join(delimiter);
Or the use of regular expressions :或者使用正则表达式:
result = inputString.replace(/,[^,]*$/, "");
Try this试试这个
var string = "Welcome, to, this, site";
var ss = string.split(",");
var newstr = "";
for(var i=0;i<ss.length-1;i++){
if (i == ss.length-2)
newstr += ss[i];
else
newstr += ss[i]+", ";
}
alert(newstr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.