Trim trailing char

Benchmark created by Jens Roland on


Preparation HTML

<script>
  var strW = '1,10010,300,';
  var strWO = '1,10010,300';
  var str;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
CharAt and substring
if (strW.charAt(strW.length - 1) == ',') {
 str = strW.substring(0, strW.length - 1);
}

if (strWO.charAt(strWO.length - 1) == ',') {
 str = strWO.substring(0, strWO.length - 1);
}
ready
Regex replace
str = strW.replace(/^(.*[^\,])\,*$/, "$1");

str = strWO.replace(/^(.*[^\,])\,*$/, "$1");
ready
Slice hack
str = strW + ',,';
str = str.slice(0, str.indexOf(',,'));
str = strWO + ',,';
str = str.slice(0, str.indexOf(',,'));
ready
Simpler regex
str = strW.replace(/\,$/, '');

str = strWO.replace(/\,$/, '');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Jens Roland on