Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove first 5 or 7 characters using javascript

Tags:

javascript

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

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

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.

like image 422
usman610 Avatar asked Aug 23 '13 12:08

usman610


People also ask

How do I remove the first 4 characters in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.

How do I remove a specific part of a string in JavaScript?

To remove all occurrences of a substring from a string, call the replaceAll() method on the string, passing it the substring as the first parameter and an empty string as the second. The replaceAll method will return a new string, where all occurrences of the substring are removed.


2 Answers

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:

"orld!"

|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"
like image 178
SpYk3HH Avatar answered Oct 06 '22 09:10

SpYk3HH


You can use substr with 1 parameter. This will cut the first x characters from the string and return the remaining.

var foo = '12345String starts here';
alert(foo.substr(5)); // = "String starts here"

How you determine where to cut the string is up to you, as your question does not include enough detail.

like image 23
Rory McCrossan Avatar answered Oct 06 '22 11:10

Rory McCrossan