For removing a part of the string in JS you have to use the slice method.
You have to pass the start and end parameter value in the slice() method. A slice method will return the extracted parts in a new string. Where a first character has position will be 0 and the second has position 1, and so on.
If you want string from the end then use negative number values.
Let’s see a simple example. In the string, we are slice the string from 0 to 5 character and showing it’s in an alert box.
<!DOCTYPE html> <html> <script> var str = "Hello world!"; var sb = str.slice(0, 5); alert(sb); </script> <body> </body> </html>
Q: How to Extract the whole string in JS?
Answer: use the slice method with 0 value. See the below example for it.
<script> var str = "Hello world!"; var sb = str.slice(0); alert(sb); </script>
array.slice( begin [,end] );
<!DOCTYPE html> <html> <script> var arr = ["John", "Alley", "King", "Tim", "Rock"]; document.write("arr.slice( 0, 2) : " + arr.slice( 1, 2) ); document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) ); </script> <body> </body> </html>
Note: The original array will not be changed.
Do comment if you have any doubts and questions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.