String: string s = "1,2,3,4,5,"
Goal: Delete the last ","
Method:
The most commonly used one is substring, this is what I always use too
s=s.substring(0,s.length-1)
I often encounter this kind of thing recently. For example, there is a string "[lightinthebox]", but I just need lightinthebox, not "[]". How to remove it quickly and effectively.
stringObject.substring(start,stop) //The start and end strings are intercepted.
stringObject.substr(start,length) //The start and string length are intercepted.
Taking these into account, and method concatenation.
stringObject.substr(1).substring(-1,0) //It’s feasible
By the way, here is an interception time. Nowadays, there are people who want to change the one digit into two digits. For example, 9 is displayed as 09 to facilitate format alignment.
In many places, it is judged whether the number is less than 10 to determine whether to add 0
If we use strings, there is no need to judge, just add one digit and intercept the last two digits. 01, 010, 011 becomes 01 10 011
I won’t go into details, lest anyone laugh at me
Later, because the Script House backend needed to add some small functions, I specially added a function to first determine whether the last character is correct and then replace it
<SCRIPT type="text/javascript"> function delfh(str){ str=str.replace(",,",","); if(str.substring(str.length-1,str.length)==","){ str2=str.substring(0,str.length-1); delfh(str2); }else{ str2=str; } return str2; } var s2="1,,,2,,,,3,,,,4,54,454,,,,,,,,,,,,,,,,"; var s="415929,415930,415931,415932,415933,415934,415935,415936,415937,415938,415939,415940,415941,415942,415943,415944,415945,415946,415947,415948,1,2,3"; alert(delfh(s2)); </script>
No problem after testing.