I got a quick question, I got the following code
String chapterNumber = "14.2.1";
how can I achieve to get a String like the following out of my "chapterNumber"
String mainChapterNumber = "14";
Edit: I want all the numbers in an int/String (doesn't matter to me) up to the first point
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .
trim() so it can remove the spaces in start and in end. Don't forget to trim the string.
s1. trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.)
If it's only the first portion of the input string you want, you should do
String mainChapterNumber = chapterNumber.split("\\.", 2)[0];
The second argument of split
(2
) indicates that we should only split on the first occurrence of .
; it's faster than splitting on all instances of .
which is what would happen if we didn't supply this second argument.
Relevant Documentation
split
Just use the following:
String mainChapterNum = chapterNumber.substring(0, chapterNumber.indexOf("."));
This will return a substring of your current chapter number starting from the first character which is placed in index number 0 and ending before the first appearance of "."
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