You can use substring or slice method to Get first n characters of string in JavaScript. Where n could be any number 1,2,3… so on. Get first n characters of string JavaScript Examples HTML examples code: Let’s get first 4 char from string in JS. Using substring() Method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE HTML> <html> <body> <script> var str = "HELLO WORLD"; var res = str.substring(0, 4); alert(res); </script> </body> </html> |
Using slice() Method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE HTML> <html> <body> <script> var str = "HELLO WORLD"; var res = str.slice(0,4); alert(res); </script> </body> </html> |
Output: Result Read More…