I'm having trouble to figure out how to count vowels, consonants and declare how often the vowels appears separately, from user input.
The user put any text ex: “Mischief managed!” and result must be:
a: 2
e: 2
i: 2
o: 0
u: 0
non-vowels: 11
var userData = prompt ("Enter any text here");
var a = 0;
var e = 0;
var i = 0;
var o = 0;
var u = 0;
var consonants = 0;
var count;
for (count = 0; count <= userData.legth; count++){
if((userData.charAt(count).match(/[aeiou]/))){
a++;
e++;
i++;
o++;
u++;
}else if((userData.charAt(count).match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/))){
consonants++;
}
}
console.log ("a: " + a);
console.log ("e: " + e);
console.log ("i: " + i);
console.log ("o: " + o);
console.log ("u: " + u);
console.log ("consonants: " + consonants);
But it's not working. I already searched in many other forums but, I didn't find anything like this.
Firstly, let's point out some things
for (count = 0; count <= userData.legth; count++){
Length is missing letter 'n' and you don't need count to be less than or equal because you already start from index 0. So you just need less than.
Also:
if((userData.charAt(count).match(/[aeiou]/))){
a++;
e++;
i++;
o++;
u++;
} else if((userData.charAt(count).match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/))){
consonants++;
}
What you are doing here is that every time it matches a vowel, you increment the variable for all of them, so for the word hi it would print that every vowel had one count. So take a look at this one:
var userData = prompt("Enter any text here").toLowerCase();
var a = 0;
var e = 0;
var i = 0;
var o = 0;
var u = 0;
var consonants = 0;
var count;
for (count = 0; count < userData.length; count++){
var char = userData.charAt(count);
if(char.match(/[aeiou]/)){
switch (char) {
case 'a':
a++;
break;
case 'e':
e++;
break;
case 'i':
i++;
break;
case 'o':
o++;
break;
case 'u':
u++;
break;
}
} else if(char.match(/[bcdfghjklmnpqrstvwxyz]/)) {
consonants++;
}
}
console.log ("a: " + a);
console.log ("e: " + e);
console.log ("i: " + i);
console.log ("o: " + o);
console.log ("u: " + u);
console.log ("consonants: " + consonants);
I am following your logic to keep it simple and better readable for you. We match the regular expression the same way you do, but we also check what is the exact character right now, so we can increment the correct variable.
For the else if, in order to minimize a bit your regular expression we just check if it matches one of the lower case letters, because we convert the userData to lower case, as soon as we get it:
var userData = prompt("Enter any text here").toLowerCase();
Try my example and see if it fits your needs.
Well, you need to check which vowel you're encountering and then update
the appropriate variable.
But for is rarely needed. JavaScript provides higher-level array
iteration functions which among other things, will prevent mistakes such
as off-by-one errors, like you have in your code :-)
And though your input is a string, not an array, you can turn it
into one by using
String.prototype.split.
var input = 'Mischief managed!';
var result = input.split('').reduce(function(result, c){
c = c.toLowerCase();
if(c in result){
result[c] += 1;
}else{
result.other += 1;
}
return result;
}, {a:0, e:0, i:0, o:0, u:0, other:0});
console.log(JSON.stringify(result));
I've used Array.prototype.reduce here, but you may,
initially, find Array.prototype.forEach easier to
get your head around.
Well for the sake of better coding and performance i would do this like this;
var str = "the quick brown fOx jUmps OvEr the lazy dog";
function getVowelCount(s) {
var lut = {
a: "0",
e: "0",
i: "0",
o: "0",
u: "0"
},
a = s.split("").map(c => c.toLowerCase());
return a.reduce((p, c) => (p[c] && 1 * p[c]++, p), lut);
}
console.log(getVowelCount(str));
We can use regular expression to match vowels in a string.
Regular expression to match all occurrence of vowel in a string:/[aeiouAEIOU]+?/g
Below is the working code snippet:
//function that takes string as input
//function returns an object containing vowel count without case in account.
function vowelCount(input) {
//to get vowel count using string.match
var arrVowels =input.match(/[aeiouAEIOU]+?/g);
//acc=accumulator, curr=current value
var countVowCons= arrVowels.reduce(function (acc, curr) {
if (typeof acc[curr.toLowerCase()] == 'undefined') {
acc[curr.toLowerCase()] = 1;
}
else {
acc[curr.toLowerCase()] += 1;
}
return acc;
// the blank object below is default value of the acc (accumulator)
}, {});
countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length;
return countVowCons;
}
You could use
var userData = prompt("Enter any text here"),
count = userData.split('').reduce(function (r, a) {
var vowels = ['a', 'e', 'i', 'o', 'u'],
p = vowels.indexOf(a.toLowerCase());
if (~p) {
r[vowels[p]] = (r[vowels[p]] || 0) + 1;
} else {
r['non-vowels']= (r['non-vowels']|| 0) + 1;
}
return r;
}, Object.create(null));
console.log(count);
I would do something like this
var alpha = function(){
this.a = 0;
this.e = 0;
this.i = 0;
this.o = 0;
this.u = 0;
this.other = 0;
}
function counter(word, alpha) {
for (i = 0; i < word.length; i++) {
var chr = word.charAt(i).toLowerCase();
if (alpha.hasOwnProperty(chr)) {
alpha[chr]++;
} else {
alpha.other++;
}
}
}
function checkWord()
{
var a = new alpha();
counter("test", a);
console.log(a);
}
In action can be seen in Plunker
First count all letters and then filter what you need.
function cntLetters(inp){
var result={};
var vowels = 'aeiouy'.split('');
var inpArr=inp.split('');
for(var i=0,n=inpArr.length;i<n;i++){
result[inpArr[i]] = (result[inpArr[i]]||0)+1;
if(vowels.indexOf(inpArr[i]) > -1)
result['vowels'] = (result['vowels'] || 0) + 1;
}
return result;
}
var cnt = cntLetters('see your later');
console.log(cnt['a']);
console.log(cnt['e']);
If you want case-insensitive use var inpArr=inp.toLowerCase().split('');
This is another way to do it, but the general idea of splitting the text, looping through each letter and counting the vowels is similar to what others are posting about as well.
getCount = (str) => {
var vowelsCount = 0;
str = str.split('');
for(var i = 0; i<str.length; i++) {
if(str[i] === "a" || str[i] === "e" || str[i] === "i" || str[i] === "o" || str[i] === "u"){
vowelsCount++;
}
}
return vowelsCount;
}
console.log(getCount('onomatopoeia'));
How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));
The code below should reverse all the characters in a sentence, but it is unable to do so. This is child's play to me but at this moment it's not compiling. Can anyone figure out the issue?
Let's say:
"Smart geeks are fast coders".
The below code should reverse the above string as follows:
"trams skeeg era tsaf sredoc"
function solution(S){
var result = false;
if(S.length === 1){
result = S;
}
if(S.length > 1 && S.length < 100){
var wordsArray = S.split(" "),
wordsCount = wordsAray.length,
reverseWordsString = '';
for(var i = 0; i< wordsCount; i++){
if(i > 0){
reverseWordsString = reverseWordsString + ' ';
}
reverseWordsString = reverseWordsString + wordsAray[i].split("").reverse().join("");
}
result = reverseWordsString;
}
return result;
}
This should give you the result you're looking for.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
function reverseWords(s) {
var arr = s.split(" ");
s = '';
for(i = 0; i < arr.length; i++) {
s += arr[i].split('').reverse().join('').toLowerCase() + " ";
}
return s;
}
Wouldn't that do the job for you? Basically it just converts the string into an array, by splitting it on space. Then it loops over the array, adds every string reversed to a new string, and then it converts it to lowercase. For faster speed (nothing you would notice), you can just call newStr.toLowerCase() after the loop, so it will do it once instead of every time.
right now this stops when it reaches a character that is different between the two strings. is there a way to make it skip a character that doesn't compare?
var match = function (str1, str2) {
str1 = str1.toString(); str2 = str2.toString();
for (var i = 0; i < str1.length; i++) {
for (var j = str1.length - i; j-1; j--) {
document.body.innerHTML += str1.substr(i, j);
if (str2.indexOf(str1.substr(i, j))!== -1) {
return str1.substr(i, j);
}
}
}
return '';
}
document.body.innerHTML += (match("/some[1]/where[1]/over[3]/here[1]", "/some[1]/where[1]/over[4]/here[1]"));
http://jsfiddle.net/92taU/3/
expected: /some[1]/where[1]/over[]/here[1]
this does what are you looking for:
var match = function (str1, str2) {
str1 = str1.toString(); str2 = str2.toString();
ret=''; i=0; j=0; l=str1.length; k=0; m=0;
while(i<l && j<l)
{
// If char is equal just add!
if(str1[i]==str2[j])
{
ret+=str1[i];
i++;
j++;
} else {
// If it's different search next equal char...
for(k=i;k<l;k++)
{
for(m=j;m<l;m++)
{
if(str1[k]==str2[m])
{
// if char is found adjust indexes and break current for
i=k;
j=m;
k=l; // to break m for
break;
}
}
}
}
}
return ret;
}
document.body.innerHTML += (match("/some[1]/where[1]/over[3]/here[1]", "/some[1]/where[1]/over[4]/here[1]"));
It returns:
/some[1]/where[1]/over[]/here[1]
Different lengths are allowed.
I'm assuming the two strings you're comparing will always be the same length. Here's some code that should do what I think you're asking for:
var match = function (str1, str2) {
var i = 0;
while (i < str1.length) {
if (str1.substr(i, 1) !== str2.substr(i, 1)) {
break;
}
i++;
}
if (i === str1.length) {
return str1;
} else {
return str1.substr(0, i) + match(str1.substr(i + 1), str2.substr(i + 1));
}
}
document.body.innerHTML += (match("/some[1]/where[1]/over[3]/here[1]", "/some[1]/where[1]/over[4]/here[1]"));
Starting at the beginning of each string, this code finds the longest substring. When a mismatch is found, it grabs that matching substring, skips the next character and repeats the process using a recursive function call on the remaining characters from each string.
I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(unique.indexOf(string[i])==-1){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
We can also now clean things up using filter method:
function removeDuplicateCharacters(string) {
return string
.split('')
.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
.join('');
}
console.log(removeDuplicateCharacters('baraban'));
Working example:
function find_unique_characters(str) {
var unique = '';
for (var i = 0; i < str.length; i++) {
if (str.lastIndexOf(str[i]) == str.indexOf(str[i])) {
unique += str[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
console.log(find_unique_characters('anaconda'));
If you only want to return characters that appear occur once in a string, check if their last occurrence is at the same position as their first occurrence.
Your code was returning all characters in the string at least once, instead of only returning characters that occur no more than once. but obviously you know that already, otherwise there wouldn't be a question ;-)
Just wanted to add my solution for fun:
function removeDoubles(string) {
var mapping = {};
var newString = '';
for (var i = 0; i < string.length; i++) {
if (!(string[i] in mapping)) {
newString += string[i];
mapping[string[i]] = true;
}
}
return newString;
}
With lodash:
_.uniq('baraban').join(''); // returns 'barn'
You can put character as parameter which want to remove as unique like this
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
let result = find_unique_characters("aaaha ok yet?", "a");
console.log(result);
//One simple way to remove redundecy of Char in String
var char = "aaavsvvssff"; //Input string
var rst=char.charAt(0);
for(var i=1;i<char.length;i++){
var isExist = rst.search(char.charAt(i));
isExist >=0 ?0:(rst += char.charAt(i) );
}
console.log(JSON.stringify(rst)); //output string : avsf
For strings (in one line)
removeDuplicatesStr = str => [...new Set(str)].join('');
For arrays (in one line)
removeDuplicatesArr = arr => [...new Set(arr)]
Using Set:
removeDuplicates = str => [...new Set(str)].join('');
Thanks to David comment below.
DEMO
function find_unique_characters( string ){
unique=[];
while(string.length>0){
var char = string.charAt(0);
var re = new RegExp(char,"g");
if (string.match(re).length===1) unique.push(char);
string=string.replace(re,"");
}
return unique.join("");
}
console.log(find_unique_characters('baraban')); // rn
console.log(find_unique_characters('anaconda')); //cod
var str = 'anaconda'.split('');
var rmDup = str.filter(function(val, i, str){
return str.lastIndexOf(val) === str.indexOf(val);
});
console.log(rmDup); //prints ["c", "o", "d"]
Please verify here: https://jsfiddle.net/jmgy8eg9/1/
Using Set() and destructuring twice is shorter:
const str = 'aaaaaaaabbbbbbbbbbbbbcdeeeeefggggg';
const unique = [...new Set([...str])].join('');
console.log(unique);
Yet another way to remove all letters that appear more than once:
function find_unique_characters( string ) {
var mapping = {};
for(var i = 0; i < string.length; i++) {
var letter = string[i].toString();
mapping[letter] = mapping[letter] + 1 || 1;
}
var unique = '';
for (var letter in mapping) {
if (mapping[letter] === 1)
unique += letter;
}
return unique;
}
Live test case.
Explanation: you loop once over all the characters in the string, mapping each character to the amount of times it occurred in the string. Then you iterate over the items (letters that appeared in the string) and pick only those which appeared only once.
function removeDup(str) {
var arOut = [];
for (var i=0; i < str.length; i++) {
var c = str.charAt(i);
if (c === '_') continue;
if (str.indexOf(c, i+1) === -1) {
arOut.push(c);
}
else {
var rx = new RegExp(c, "g");
str = str.replace(rx, '_');
}
}
return arOut.join('');
}
I have FF/Chrome, on which this works:
var h={};
"anaconda".split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("")
Which you can reuse if you write a function like:
function nonRepeaters(s) {
var h={};
return s.split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("");
}
For older browsers that lack map, filter etc, I'm guessing that it could be emulated by jQuery or prototype...
This code worked for me on removing duplicate(repeated) characters from a string (even if its words separated by space)
Link: Working Sample JSFiddle
/* This assumes you have trim the string and checked if it empty */
function RemoveDuplicateChars(str) {
var curr_index = 0;
var curr_char;
var strSplit;
var found_first;
while (curr_char != '') {
curr_char = str.charAt(curr_index);
/* Ignore spaces */
if (curr_char == ' ') {
curr_index++;
continue;
}
strSplit = str.split('');
found_first = false;
for (var i=0;i<strSplit.length;i++) {
if(str.charAt(i) == curr_char && !found_first)
found_first = true;
else if (str.charAt(i) == curr_char && found_first) {
/* Remove it from the string */
str = setCharAt(str,i,'');
}
}
curr_index++;
}
return str;
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
Here's what I used - haven't tested it for spaces or special characters, but should work fine for pure strings:
function uniquereduce(instring){
outstring = ''
instringarray = instring.split('')
used = {}
for (var i = 0; i < instringarray.length; i++) {
if(!used[instringarray[i]]){
used[instringarray[i]] = true
outstring += instringarray[i]
}
}
return outstring
}
Just came across a similar issue (finding the duplicates). Essentially, use a hash to keep track of the character occurrence counts, and build a new string with the "one-hit wonders":
function oneHitWonders(input) {
var a = input.split('');
var l = a.length;
var i = 0;
var h = {};
var r = "";
while (i < l) {
h[a[i]] = (h[a[i]] || 0) + 1;
i += 1;
}
for (var c in h) {
if (h[c] === 1) {
r += c;
}
}
return r;
}
Usage:
var a = "anaconda";
var b = oneHitWonders(a); // b === "cod"
Try this code, it works :)
var str="anaconda";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){
return obj;
}
}
).join("");
//output: "cod"
This should work using Regex ;
NOTE: Actually, i dont know how this regex works ,but i knew its 'shorthand' ,
so,i would have Explain to you better about meaning of this /(.+)(?=.*?\1)/g;.
this regex only return to me the duplicated character in an array ,so i looped through it to got the length of the repeated characters .but this does not work for a special characters like "#" "_" "-", but its give you expected result ; including those special characters if any
function removeDuplicates(str){
var REPEATED_CHARS_REGEX = /(.+)(?=.*?\1)/g;
var res = str.match(REPEATED_CHARS_REGEX);
var word = res.slice(0,1);
var raw = res.slice(1);
var together = new String (word+raw);
var fer = together.toString();
var length = fer.length;
// my sorted duplicate;
var result = '';
for(var i = 0; i < str.length; i++) {
if(result.indexOf(str[i]) < 0) {
result += str[i];
}
}
return {uniques: result,duplicates: length};
} removeDuplicates('anaconda')
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
I have 3 loopless, one-line approaches to this.
Approach 1 - removes duplicates, and preserves original character order:
var str = "anaconda";
var newstr = str.replace(new RegExp("[^"+str.split("").sort().join("").replace(/(.)\1+/g, "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")+"]","g"),"");
//cod
Approach 2 - removes duplicates but does NOT preserve character order, but may be faster than Approach 1 because it uses less Regular Expressions:
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)\1+/g, "");
//cdo
Approach 3 - removes duplicates, but keeps the unique values (also does not preserve character order):
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
//acdno
function removeduplicate(str) {
let map = new Map();
// n
for (let i = 0; i < str.length; i++) {
if (map.has(str[i])) {
map.set(str[i], map.get(str[i]) + 1);
} else {
map.set(str[i], 1);
}
}
let res = '';
for (let i = 0; i < str.length; i++) {
if (map.get(str[i]) === 1) {
res += str[i];
}
}
// o (2n) - > O(n)
// space o(n)
return res;
}
If you want your function to just return you a unique set of characters in your argument, this piece of code might come in handy.
Here, you can also check for non-unique values which are being recorded in 'nonUnique' titled array:
function remDups(str){
if(!str.length)
return '';
var obj = {};
var unique = [];
var notUnique = [];
for(var i = 0; i < str.length; i++){
obj[str[i]] = (obj[str[i]] || 0) + 1;
}
Object.keys(obj).filter(function(el,ind){
if(obj[el] === 1){
unique+=el;
}
else if(obj[el] > 1){
notUnique+=el;
}
});
return unique;
}
console.log(remDups('anaconda')); //prints 'cod'
If you want to return the set of characters with their just one-time occurrences in the passed string, following piece of code might come in handy:
function remDups(str){
if(!str.length)
return '';
var s = str.split('');
var obj = {};
for(var i = 0; i < s.length; i++){
obj[s[i]] = (obj[s[i]] || 0) + 1;
}
return Object.keys(obj).join('');
}
console.log(remDups('anaconda')); //prints 'ancod'
function removeDuplicates(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result +=char;
}
}
return result;
}
console.log(("anaconda").split('').sort().join('').replace(/(.)\1+/g, ""));
By this, you can do it in one line.
output: 'cdo'
function removeDuplicates(string){
return string.split('').filter((item, pos, self)=> self.indexOf(item) == pos).join('');
}
the filter will remove all characters has seen before using the index of item and position of the current element
Method 1 : one Simple way with just includes JS- function
var data = 'sssssddddddddddfffffff';
var ary = [];
var item = '';
for (const index in data) {
if (!ary.includes(data[index])) {
ary[index] = data[index];
item += data[index];
}
}
console.log(item);
Method 2 : Yes we can make this possible without using JavaScript function :
var name = 'sssssddddddddddfffffff';
let i = 0;
let newarry = [];
for (let singlestr of name) {
newarry[i] = singlestr;
i++;
}
// now we have new Array and length of string
length = i;
function getLocation(recArray, item, arrayLength) {
firstLaction = -1;
for (let i = 0; i < arrayLength; i++) {
if (recArray[i] === item) {
firstLaction = i;
break;
}
}
return firstLaction;
}
let finalString = '';
for (let b = 0; b < length; b++) {
const result = getLocation(newarry, newarry[b], length);
if (result === b) {
finalString += newarry[b];
}
}
console.log(finalString); // sdf
// Try this way
const str = 'anaconda';
const printUniqueChar = str => {
const strArr = str.split("");
const uniqueArray = strArr.filter(el => {
return strArr.indexOf(el) === strArr.lastIndexOf(el);
});
return uniqueArray.join("");
};
console.log(printUniqueChar(str)); // output-> cod
function RemDuplchar(str)
{
var index={},uniq='',i=0;
while(i<str.length)
{
if (!index[str[i]])
{
index[str[i]]=true;
uniq=uniq+str[i];
}
i++;
}
return uniq;
}
We can remove the duplicate or similar elements in string using for loop and extracting string methods like slice, substring, substr
Example if you want to remove duplicate elements such as aababbafabbb:
var data = document.getElementById("id").value
for(var i = 0; i < data.length; i++)
{
for(var j = i + 1; j < data.length; j++)
{
if(data.charAt(i)==data.charAt(j))
{
data = data.substring(0, j) + data.substring(j + 1);
j = j - 1;
console.log(data);
}
}
}
Please let me know if you want some additional information.