admin管理员组文章数量:1277896
Given a string like this:
"boy, girl, dog, cat"
What would be a good way to get the first word and the rest of them, so I could have this:
var first_word = "boy";
var rest = "girl, dog, cat";
Right now I have this:
my_string.split(",");
But that gives me all the words that are between the mas.
Given a string like this:
"boy, girl, dog, cat"
What would be a good way to get the first word and the rest of them, so I could have this:
var first_word = "boy";
var rest = "girl, dog, cat";
Right now I have this:
my_string.split(",");
But that gives me all the words that are between the mas.
6 Answers
Reset to default 4You can use both split
and splice
:
var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");
Or similar
// returns an array with the extracted str as first value
// and the rest as second value
function cutFirst(str,token){
var arr = str.split(token);
var fst = arr.splice(0,1);
return [fst.join(""),arr.join(token)];
}
Use a bination of substring()
(returning the substring between two indexes or the end of the string) and indexOf()
(returning the first position of a substring within another string):
var input = "boy, girl, dog, cat",
pos = input.indexOf( ',' );
console.log( input.substring( 0, pos ) );
console.log( input.substring( pos + 1 ) );
Maybe you want to add an trim()
call to the results to remove whitespaces.
You can use a regex to match the two strings before and after the first ma:
var v = "boy, girl, dog, cat";
var strings = v.match(/([^,]*),(.*)/);
Now strings
will be a three element array where
strings[0]
contains the full stringstrings[1]
contains the string before the first mastrings[2]
contains everything after the first ma
You can create an array in a lazy way and then retrieve just the first element.
var ArrayFromString = "boy, girl, dog, cat".split(",");
firstElement = ArrayFromString.pop();
alert(firstElement); //boy
alert(ArrayFromString); //girl, dog, cat
Yet another option is to split the array, get first and join the rest:
var my_string = "boy, girl, dog, cat";
var splitted = my_string.split(',');
var first_item = splitted.shift();
var rest_of_the_items = splitted.join(',');
console.log(first_item); // 'boy'
console.log(rest_of_the_items); // 'girl, dog, cat'
const my_string = "boy, girl, dog, cat";
const splitted = my_string.split(',');
splitted.forEach(element => console.log(element));
You can also them like an array:
console.log(\`This is a ${splitted\[0\]}\`);
// expected output: "boy"
// expected output: " girl"
// expected output: " dog"
// expected output: " cat"
本文标签: Get first and rest of string from comma separated values in JavascriptStack Overflow
版权声明:本文标题:Get first and rest of string from comma separated values in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741301890a2371136.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论