split() with regex or using
split() with regex
A string item’s parted technique partitions the string into various substrings and returns the new cluster. If the parameter is the empty string “,” the string will be divided in half. In addition to the method’s parameters, here is how to write it.
- separator: Specifies the character, or regular expression, to split the string. If omitted, the entire string is returned (an array with only one item).
- limit: An integer specifying the number of splits. Items after the division limit will not be included in the array.
When we use the
split() method with the string to split and pass the regex definition for how to split the string, we will get the following result:
var splitString = "842.344.learnshareit".split(/\.(?=[^\.]+$)/); console.log(splitString);
By using regex, we can define for the program to know at what point the string should be split, specifically here at the last dot. The return value on our console will be the number after this dot. Or you can also refer to the method below.
The slice() method is used to get (extract) part of the array. We can use this method with an array to get the value at any position, so first, we need to find the position of the last “.” by using the
lastIndexOf() method and passing it a dot character parameter.
var splitString = "842.344.learnshareit".split(/\.(?=[^\.]+$)/); var index = splitString.lastIndexOf("."); var after = splitString.slice(index + 1); console.log(after);
Like the code above, we use the
slice() method to slice the string into a two-valued array consisting of the part before the last dot and the part after it. We need to print the element value with an index of 1 to have the same result as the first way.
Split() with regex will be much more compact, but you must understand how to custom regex.
Maybe you are interested:
Name of the university: PTIT