What is a string?
Using substring() to extract a substring
Here are some examples of using substring() to extract a substring using the substring() function.
<!DOCTYPE html> <html> <body> <h2> The substring() extracts a part of a string </h2> <p id="demo"> </p> <script> let text = "The greatest glory in living lies not in never falling, but in rising every time we fall."; let result = text.substring(1, 4); //extracts the characters from the position 1 to 4 document.getElementById("demo").innerHTML = result; </script> </body> </html>
Explaining the above program:
- Here, The variable text stores the string, and the result variable will store the extracted substring.
- The id attribute used is for defining the HTML element.
- In the line, let result = text.substring(1, 4), the function substring() gets called, and passing parameters (1,4) will separate the characters from position 1 to 4 and store it in the result variable.
- Lastly, return the extracted substring stored in the result using the innerHTML method.
Extract a substring using the split() function
Similar to the substring(), the split() function also returns a part of a string. The string gets divided and the separation depends on the parameter we pass to the split() function. The split() function will split every character in the string if ("") is the parameter, and it will separate the words if (" ") is the parameter.
<!DOCTYPE html> <html> <body> <h1>Program to extract a substring from a string</h1> <h2>Extract the desired word from a string</h2> <p>The second word is:</p> <p id="demo"></p> <script> let text = "How are you doing today?"; const myArray = text.split(" ");//The split(" ") function divides the string into an array of words document.getElementById("demo").innerHTML = myArray;//prints the the third word from the divided string </script> </body> </html>
Working of the program:
- Here, the variable text stores the string, and the id attribute will define the HTML element.
- In the line, const myArray = text.split(" "), the split() function will separate the string stored in the variable text. Every word gets split and stored in the myArray array.
- Lastly, it will return the substring from the array using the innerHTML method.