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.
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.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With