javascript counting vowels, consonants and show the occurrance - javascript

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'));

Related

How to ignore spaces in string indexes and start with a capital letter on each word in a sentence

Basically, I have this code, where I want to change a given string to wEiRd CaSe, alternate between indexes, for example:
Starting from index 0 I want the letter to be capital, and then when the index got to an odd number, like 1, 3, 5, etc... I want to change it to uppercase.
So:
Stackoverflow should be StAcKoVeRfLoW, But I also want to work with strings, strings like this
This is a test should be: ThIs Is A TeSt
But my function returns : ThIs iS A TeSt
Here's my code:
"use strict";
var weirdCase = function(string) {
var characters = string.split("");
characters.forEach(function(value, index, characters) {
// If the index is even
if (index % 2 == 0) {
characters[index] = value.toUpperCase();
} else {
characters[index] = value.toLowerCase();
}
});
return characters.join("");
}
My question might be a bit misleading, I wanted to be wEiRd Case but also the first letter of the words to be capital, So I did this:
function toWeirdCase(string){
return string.split(' ').map(function(word){
return word.split('').map(function(letter, index){
return index % 2 == 0 ? letter.toUpperCase() : letter.toLowerCase()
}).join('');
}).join(' ');
}
Hope this helps someone
You can add another variable charIndex which you increase manually only if the value is no space. charIndex will represent the indexes for your string like it has no spaces in it.
"use strict";
var weirdCase = function(string) {
var characters = string.split("");
var charIndex = 0;
characters.forEach(function(value, index, characters) {
//Exclude spaces
if (value === " ") {
return;
}
// If the index is even
if (charIndex % 2 == 0) {
characters[index] = value.toUpperCase();
} else {
characters[index] = value.toLowerCase();
}
//Increment charIndex
charIndex += 1;
});
return characters.join("");
}
Should be as simple as this:
function WeIrDcAsE(string) {
let isUpperCase = true;
let result = '';
for (let character of string) {
if (isUpperCase) {
result += character.toUpperCase();
} else {
result += character.toLowerCase();
}
if (character.match(/[a-zA-Z]/)) {
isUpperCase = !isUpperCase;
} else {
isUpperCase = true;
}
}
return result;
}
console.log(WeIrDcAsE("This is a test!"));
In a much more simpler way...
a = "This is a test"
b = a.split('')
counter = 0
c = b.map(function(c) {
if (c === ' ') return c
if ((counter % 2) === 0) {
counter++
return c.toUpperCase()
}
counter++
return c.toLowerCase()
})
console.log(c.join(''))
This code can be simplified a lot, I think.
var weirdCase = function(str){
var upper = false;
for (var i = 0; i < str.length; i++){
if (str[i] != ' '){
if (upper){
str[i] = character.toUpperCase();
}else{
str[i] = character.toLowerCase();
}
upper = !upper;
}
}
I would do as follows;
var str = "this is a test",
result = str.split(" ")
.map(s => [].reduce
.call(s, (p,c,i) => p += i & 1 ? c.toLowerCase()
: c.toUpperCase(),""))
.join(" ");
console.log(result);
var string= 'Stackoverflow';
for (var i=0; i<string.length; i+=2)
string= string.substr(0,i) + string[i].toUpperCase() + string.substr(i+1);
Nev er mid, scratch this: I need to read more carefully, sorry.

Each Character occurrence in a string

How to write a javascript code that counts each character occurrence in a string ?
e.g
String is : Hello World
Output :
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
var counts = {};
yourstring.split('').map(function(ch) {
counts[ch] = (counts[ch] || 0) + 1;
});
Or be hip and use map/reduce:
var counts = yourstring.split('').reduce(function(dst, c) {
dst[c] = (dst[c] || 0) + 1;
return dst;
}, {});
this code should work:
var str = "Hello World";
var arr = str.split('');
var occ = {};
for(var i=0,c=arr.length;i<c;i++){
if(occ[arr[i]]) occ[arr[i]]++;
else occ[arr[i]] = 1;
}
for(var i in occ){
alert('count of '+i+' -> '+occ[i]);
}
var splitWord = "Hello World".split('');
var letters = {};
for(var i in splitWord)
{
var letter = splitWord[i];
if(letter == ' ') continue;
if(typeof letters[letter] == 'undefined')
{
letters[letter] = 0;
}
letters[letter]++;
}
console.dir(letters);
Below is my solution with the old and simple for loop. This approach answers the question in the simplest possible way for beginners.
This code will convert all the letters in the input to lower case and count their occurrence. In this solution, we also count the special characters and spaces as valid characters.
function countChar(str) {
var count = {};
for (let i = 0; i < str.length; i++) {
var ch = str[i].toLowerCase();
if (count[ch] > 0) {
count[ch]++;
} else {
count[ch] = 1;
}
}
return count;
}
The count object denotes the characters in the input.

Showing unique characters in a string only once

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Find the characters in a string which are not duplicated

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.

Matching only characters in sequence of a word from a given string

I am trying to find a closest match for a word by giving a specific string, for example:
so I would have:
"jonston" x "john" => "jo" //only "jo" is the part that matches
"joshua" x "john" => "jo"
"mark" x "marta" => "mar"
as you can see I only would like to retrieve the characters in sequence matching, that's why joshua and john only would have jo in common sequence and not joh since both have the letter h
I've tried that with regular expression by using the following:
"john".match(/["joshua"]+/) //=> outputs ["joh"] and not ["jo"]
is there any way I could match only the first chars that match?
I will be using javascript for the implementation
I hope that makes sense
Thanks in advance
initLCS = function(a, b) {
for (var i = 0; i < a.length && a[i] == b[i]; i++);
return a.substr(0, i);
}
initLCS("jonston", "john") // jo
initLCS("jonston", "j111") // j
initLCS("xx", "yy") // ""
If you insist on using regular expressions, it goes like this:
initLCS = function(a, b) {
function makeRe(x) {
return x.length ? "(" + x.shift() + makeRe(x) + ")?" : "";
}
var re = new RegExp('^' + makeRe(b.split("")), "g");
return a.match(re)[0];
}
This creates an expression like /^(j(o(h(n)?)?)?)?/g from the second string and applies it to the first one. Not that it makes much sense, just for the heck of it.
var a = "john";
var b = "joshua";
var x = "";
for (var i = 0; i < a.length; i++) {
if (x == "" && i > 0) break;
else if (a[i] == b[i]) x += a[i];
else if (x != "") break;
}
console.log(x);
DEMO: http://jsfiddle.net/jMuDm/
Yet another solution:
if(typeof String.prototype.commonFirstChars !== 'function') {
String.prototype.commonFirstChars = function(s) {
var common = "";
for(var i=0; i<this.length; i++) {
if(this[i] !== s[i]) {
return common;
}
common += this[i];
}
};
}
You can use it like this:
var commonFirstChars = "john".commonFirstChars("joshua");
// "john".commonFirstChars("joshua") === "joshua".commonFirstChars("john")
This will return:
jo
You can not really do this with regex. Why dont you just loop through both string and compare the indexes? You can select the chars until you hit a char at the same index with a different value.
I'd do this in a recursive function like this:
EDIT: Updated example to make it more readable.
var testWords = [
['ted', 'terminator'],
['joe', 'john'],
['foo', 'bar']
];
var matches = testWords.map(function(wordPair) {
return (function matchChars(word1, word2, matches) {
if (word1[0] !== word2[0]) {
return [wordPair[0], wordPair[1], matches];
}
matches = matches || '';
matches += word1[0];
return matchChars(word1.slice(1), word2.slice(1), matches);
}(wordPair[0], wordPair[1]));
});
console.log(matches.map(function(match) { return match.join(', '); }).join('\n'));
​
Fiddle (updated): http://jsfiddle.net/VU5QT/2/

Categories