- By using String.split() method
- By using Regular Expressions with RegExp.exec() method
- By using String.indexOf() and String.substring() methods
Let’s explore each…
#1 – By using String.split() method
let fruits = "apple,banana,grape"; let fruitsArray = fruits.split(","); console.log(fruitsArray); // ["apple", "banana", "grape"]
How it works
String.split() method divides a string into an ordered set of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern (specified separator) and separating the string whenever the pattern is found. If separator is an empty string, str is converted to an array of characters.
split()method is called on the string you want to divide.
- The character or characters you want to use as the split point are passed as an argument to the method.
- The method then goes through the string and every time it finds the character or characters it splits the string at that point.
- It returns the sections of the string as elements in an array.
- In our case, the string “apple,banana,grape” is split at each comma, resulting in the array [“apple”, “banana”, “grape”].
#2 – By using Regular Expressions with RegExp.exec() method
var myRegEx = /(d+)/g; var myString = "I have 100 apples and 200 oranges"; var result = myRegEx.exec(myString); console.log(result);
How it works
The RegExp.exec() method executes a search for a match in a specified string and returns an array of information or null on a mismatch.
- The regular expression
/(d+)/gis created, where d matches any digit (equivalent to [0-9]), + causes the engine to match the preceding character 1 or more times, and g is for global search (doesn’t return after the first match).
- A string, ‘I have 100 apples and 200 oranges’, is defined to be searched against the regular expression.
- The exec() method is used on the regular expression with the string as an argument, which returns an array of results.
- The array contains the matched strings along with their index positions and input strings. In this case, it contains ‘100’ from the position 7 and ‘200’ from the position 22.
#3 – By using String.indexOf() and String.substring() methods
var str = "Hello, World!"; var index = str.indexOf("World"); var substring = str.substring(index, index + "World".length);
How it works
- Firstly, we define a string
str = "Hello, World!".
- Then we use the
indexOf()method on the string
strto find the index at which the substring
"World"begins. This will return the value 7, which is the position of
"W"in the string
- We store this index in the variable
- Next, we use the
substring()method on the string
strto extract the substring that starts at the index found in the previous step and ends at the index representing the end of the substring we want to extract. This end index is calculated as
index + "World".length.
- The string
substringnow holds the value “World”.