Programming Examples

JavaScript function to extract unique characters from a string


Write a JavaScript function to extract unique characters from a string.

Example string : "thequickbrownfoxjumpsoverthelazydog"

Expected Output : "thequickbrownfxjmpsvlazydg"

Solution

<!DOCTYPE HTML>
<html>
	<head>
		<title>Unique Character</title>
		<style type="text/css">
			.error_msg
			{
				color:#ff0000;
				font-style:italic;
			}
		</style>
		<script language="javascript">
			function unique_char()
			{
				var data=document.getElementById('user_txt').value;
				document.getElementById('error').innerHTML="";
				document.getElementById('result').innerHTML="";
				var unique='';
				var i,j;
				if(data=="")
				{
					document.getElementById('error').innerHTML="Please Enter the text";
				}
				else
				{
					for(i=0; i<data.length; i++)
					{
						for(j=i-1; j>=0; j--)
						{
							if(data.charAt(j)==data.charAt(i))
							{
								break;
							}
						}
						if(j<0)
						{                
								unique+=data.charAt(i);
						}		
					}
					document.getElementById('result').innerHTML=unique;
				}
			}
		</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 id="error" class="error_msg"></span>
			</div>
			<div>
				<input type="button" name="check_btn" id="check_btn" value="Get Unique Char" onclick="unique_char()"/>
			</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