[英]How do I have JavaScript get a substring before a character?
假设我有一段说 55+5。 我想让 JavaScript 在加号之前返回所有内容。 这可以使用子字符串吗?
你的意思是子串而不是下标? 如果是这样的话。 好的。
var string = "55+5"; // Just a variable for your input.
function getBeforePlus(str){
return str.substring(0, str.indexOf("+"));
/* This gets a substring from the beginning of the string
to the first index of the character "+".
*/
}
否则,我建议使用String.split()方法。
你可以像这样使用它。
var string = "55+5"; // Just a variable for your input.
function getBeforePlus(str){
return str.split("+")[0];
/* This splits the string into an array using the "+"
character as a delimiter.
Then it gets the first element of the split string.
*/
}
是的。 尝试 String.split 方法: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split
split() 返回一个字符串数组,由您传递给它的字符分割(在您的情况下,加号)。 只需使用数组的第一个元素; 它将拥有加号之前的所有内容:
var string = "foo-bar-baz"
var splitstring = string.split('-')
//splitstring is a 3 element array with the elements 'foo', 'bar', and 'baz'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.