我如何让 JavaScript 在字符之前获取子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39583549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I have JavaScript get a substring before a character?
提问by johnnyjw
Let's say I have a paragraph that says 55+5. I want to have JavaScript return everything before the plus. Is this possible using substrings?
假设我有一段说 55+5。我想让 JavaScript 在加号之前返回所有内容。这可以使用子字符串吗?
回答by arjay07
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.
*/
}
回答by qxu21
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). Just use the first element of the array; it will have everything before the plus:
split() 返回一个字符串数组,由您传递给它的字符分割(在您的情况下,加号)。只需使用数组的第一个元素;它将拥有加号之前的所有内容:
var string = "foo-bar-baz"
var splitstring = string.split('-')
//splitstring is a 3 element array with the elements 'foo', 'bar', and 'baz'