Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting text strings

Status
Not open for further replies.
Aug 18, 2003
111
GB
I'm trying to format my string into uppercase and remove any alpha characters from the end of the string. For example i have a product code c8728ae which i wan't to format as C8728. I've been experimenting with the following code but it has an error somewhere. Please can someone help me. Any advice welcome.

<script language="javascript">
var str = "c8728ae";
var strUpper = str.toUpperCase();
var strLength = strUpper.length - 1;

for(i=strLength; i>=0; i--){
var tempchr = strUpper.charAt(i);
var tchr = tempchr.charCodeAt(0);

if((tchr => 60) && (tchr <= 90)){
var flag = i+1;
}
}
document.write(strUpper.substring(0,flag));
</script>
 
Gotta love regular expressions:
Code:
var str = "c8728ae";
document.write(str.toUpperCase().replace(/[A-Z]*$/,""));

Adam
 
one syntax error:
tchr => 60

should be
tchr >= 60

and this will cut off one char too many:
var flag = i+1;

try this:
Code:
<script language="javascript">
	var str = "c8728ae";
	var strUpper = str.toUpperCase();
	var strLength = strUpper.length - 1;
	var flag;

	for(i = strLength; i >= 0; i--){
			var tempchr = strUpper.charCodeAt(i);

			//  abort once we find a number
			if ((tempchr >= 48) && (tempchr <= 57)) {
				break;
			}
			//  else record position of next letter
			if((tempchr >= 60) && (tempchr <= 90)){
					flag = i;
			}
	}

	var strNew = strUpper.substring(0,flag);
	document.write(strNew);
</script>

personally, i would use a regex & String.replace():
Code:
<script language="javascript">
	var str = "c8728ae";
	var strUpper = str.toUpperCase();
	var regex = /[^\d]+$/;
	var strNew = strUpper.replace(regex, "");
	alert(strNew);
</script>

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top