Programming Examples

Write a JavaScript program which accept a string as input and swap the case of each character.


Write a JavaScript program which accept a string as input and swap the case of each character.

For example: if you input 'The Quick Brown Fox' the output should be 'tHE qUICK bROWN fOX'.

Solution

<!DOCTYPE HTML>
<html>
	<head>
		<title>Swap the Case</title>
		<style type="text/css">
			.error_msg
			{
				color:#ff0000;
				font-style:italic;
			}
		</style>
		<script language="javascript">
			function swap_case()
			{
				var data=document.getElementById('user_txt').value;
				var output='';
				document.getElementById('error').innerHTML="";
				document.getElementById('result').innerHTML="";
				var i,j;
				if(data=="")
				{
					document.getElementById('error').innerHTML="Please Enter the text";
				}
				else
				{
					for(i=0; i<data.length; i++)
					{
						if(data.charCodeAt(i)>=65&&data.charCodeAt(i)<=90)
						{                
							output+=data.charAt(i).toLowerCase();
						}
						else if(data.charCodeAt(i)>=97&&data.charCodeAt(i)<=122)
						{
							output+=data.charAt(i).toUpperCase();
						}
						else		
						{
							output+=data.charAt(i);
						}
					}
					document.getElementById('result').innerHTML=output;
				}
			}
		</script>
	</head>
	<body>	
		<form name="frm" id="frm">	
			<div>
				<label for="user_txt">Enter the Text</label>
			</div>
			<div>
				<textarea name="user_txt" id="user_txt" rows="10" cols="30"></textarea>
				<span class="error_msg" id="error"></span>
			</div>
			<div>
				<input type="button" name="check_btn" id="check_btn" value="Swap the Case" onclick="swap_case()"/>
			</div>
			<div>
				<h3>Output</h3>
				<span id="result"></span>
			</div>
			
		</form>
	</body>
</html>
Output

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz