GeezerVison is showing github.com — Created Topic substrings · codex-academy/javascript@b5119d3
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +28Lines changed: 28 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +#Substrings |
| 2 | + |
| 3 | +substring is used to take a part of a string. |
| 4 | +Syntax: substring(first_index,last_index). |
| 5 | + |
| 6 | +```js |
| 7 | +var a = 'Hello world!'; |
| 8 | +document.write(a.substring(1,6)); |
| 9 | +``` |
| 10 | +The preceding code snippet gives ```'ello '``` . Note that the 'w' (index 6) is not part of this substring. |
| 11 | + |
| 12 | +We could also do, |
| 13 | +```js |
| 14 | +var a = 'Hello world!'; |
| 15 | +document.write(a.substring(2)); |
| 16 | +``` |
| 17 | +This gives the whole string from the character with index 2. ``` 'llo world!'``` |
| 18 | + |
| 19 | +##substr |
| 20 | + |
| 21 | +There is also a method substr() that works slightly differently. Instead of the second number being an index number, |
| 22 | +it gives the number of characters. |
| 23 | +```js |
| 24 | +var a = 'Hello world!'; |
| 25 | +document.write(a.substr(1,6)); |
| 26 | +``` |
| 27 | + |
| 28 | +starts at the character with index 1 ('e') and then gives 6 characters, so the output is ```ello w``` |