Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1393 How can I strip leading and trailing characters?

You are here: irt.org | FAQ | JavaScript | Text | Q1393 [ previous next ]

Try:

<script language="javaScript"><!--
function stripLeading(string,chr) {
   var finished = false;
   for (var i = 0; i < string.length && !finished; i++)
       if (string.substring(i,i+1) != chr) finished = true;
   if (finished) return string.substring(i-1); else return string;
}

function stripTrailing(string,chr) {
   var finished = false;
   for (var i = string.length - 1; i > -1 && !finished; i--)
       if (string.substring(i,i+1) != chr) finished = true;
   if (finished) return string.substring(0,i+2); else return string;
}

function stripLeadingTrailing(string,chr) {
    return stripTrailing(stripLeading(string,chr),chr)
}

document.write('<pre>')

document.writeln(stripLeading('123','*'));
document.writeln(stripLeading('*123','*'));
document.writeln(stripLeading('**123','*'));
document.writeln(stripLeading('***123','*'));
document.writeln(stripTrailing('123','*'));
document.writeln(stripTrailing('123*','*'));
document.writeln(stripTrailing('123**','*'));
document.writeln(stripTrailing('123***','*'));
document.writeln(stripLeadingTrailing('***1*2*3***','*'));

document.write('<\/pre>')
//--></script>

©2018 Martin Webb