usman610 usman610 - 1 year ago 97
Javascript Question

how to remove first 5 or 7 characters using javascript

i have posted the a question using the given javascript below:

<script type="text/javascript">
function showData($sel){
var str='';
for (var i=0;i<sel.options.length;i++){
str+=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;
sel.form.selectedFruits.value = str;

now the question is that how to remove first 5 or 7 using this javascript. please help by setting in this javascript.

thanks in advance.

Answer Source

You could follow the substr suggestion given by Rory, but more often than not, to remove characters in JS you use the slice method. For example, if you have:

var str="Hello world!";

Removing the first 5 characters is as easy as:

var n=str.slice(5);

You parameters are very simple. The first is where to start, in this case, position 5. The second is how far to go based on original string character length, in this case, nothing since we want to go to the end of the string. The result would be:

" world!"

To remove the first 7 characters would be as easy as:

    var n=str.slice(7);

And the result would be:


|OR| if you wanted to GET the 5th to 7th character, you would use something like:

var n=str.slice(4, 7);

The reson being that it starts at position 4 meaning the first character grabbed is the 5th character. Whereas the second parameter is what character to stop at, thus use of "7". This will stop it at the 7th character thus producing:

"o w"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download