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>
▶ RUN

Output/ Explanation:

Latest Current Affairs 2025 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad