Something Like that:
slice
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13
For example I want to written Banana.
For that you need to create first html code.
HTML
<p id="demo"></p>
After that add this JS code.
JS
var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13); document.getElementById("demo").innerHTML = res;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”GvgaJM” default_tab=”js,result” user=”pradeepanvi”]See the Pen Slice in javascript 01 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6
JS
var str = "Apple, Banana, Kiwi"; var res = str.slice(-12, -6); document.getElementById("demo").innerHTML = res;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”RZNmaZ” default_tab=”result” user=”pradeepanvi”]See the Pen Slice in javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see Banana
Now I want there should be Banana, Kiwi
If you omit the second parameter, the method will slice out the rest of the string
JS
var str = "Apple, Banana, Kiwi"; var res = str.slice(7); document.getElementById("demo").innerHTML = res;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”EvazZV” default_tab=”result” user=”pradeepanvi”]See the Pen Slice in javascript 03 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
or, counting from the end
JS
var str = "Apple, Banana, Kiwi"; var res = str.slice(-12); document.getElementById("demo").innerHTML = res;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”mMyYWp” default_tab=”result” user=”pradeepanvi”]See the Pen Slice in javascript 04 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see Banana, Kiwi