[英]How do I have JavaScript get a substring before a character?
Let's say I have a paragraph that says 55+5.假设我有一段说 55+5。 I want to have JavaScript return everything before the plus.我想让 JavaScript 在加号之前返回所有内容。 Is this possible using substrings?这可以使用子字符串吗?
Do you mean substring instead of subscript?你的意思是子串而不是下标? If so.如果是这样的话。 Then yes.好的。
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 "+".
*/
}
Otherwise, I recommend using the String.split() method.否则,我建议使用String.split()方法。
You can use that like so.你可以像这样使用它。
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.
*/
}
Yes.是的。 Try the String.split method: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split尝试 String.split 方法: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split
split() returns an array of strings, split by the character you pass to it (in your case, the plus). split() 返回一个字符串数组,由您传递给它的字符分割(在您的情况下,加号)。 Just use the first element of the array;只需使用数组的第一个元素; it will have everything before the plus:它将拥有加号之前的所有内容:
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.