I wonder if it's possible to use split to devide a string with several parts that are separated with a comma, like this:
title, genre, director, actor
I just want the first part, the title of each string and not the rest?
To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.
You can use the split() method. It returns an array String[] , so you can access to an element by using the syntax someArray[index] . Since you want to get the first elemnt, you can use [0] . String first_word = s.
Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] .
The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it. It doesn't make any modifications to the original string.
string valueStr = "title, genre, director, actor"; var vals = valueStr.Split(',')[0];
vals will give you the title
Actually, there is a better way to do it than split:
public string GetFirstFromSplit(string input, char delimiter) { var i = input.IndexOf(delimiter); return i == -1 ? input : input.Substring(0, i); }
And as extension methods:
public static string FirstFromSplit(this string source, char delimiter) { var i = source.IndexOf(delimiter); return i == -1 ? source : source.Substring(0, i); } public static string FirstFromSplit(this string source, string delimiter) { var i = source.IndexOf(delimiter); return i == -1 ? source : source.Substring(0, i); }
Usage:
string result = "hi, hello, sup".FirstFromSplit(','); Console.WriteLine(result); // "hi"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With