Join the string with same separator used to split - javascript

I have a string that need to be split with a regular expression for applying some modifications.
eg:
const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/)
// ["Hello", "Beautiful", "World"]
Now the string has been split with + or #.
Now say after applying some modification to the items in the array, I have to join the array using the same separator that used to split, so the character + and # has to be in the same position as before.
eg: if i applied some modification string and joined. Then it should be.
Hello001+Beutiful002#World003
How can i do this?

When you place a pattern inside a capturing group, split will return the matched delimiters as even array items. So, all you need to do is modify the odd items:
var counter=1;
var str = "Hello+Beautiful#World";
console.log(
str.split(/([+#])/).map(function(el, index){
return el + (index % 2 === 0 ? (counter++ + "").padStart(3, '0') : '');
}).join("")
);

Don't use split and join in this case. Use String.replace(), and return the modified strings:
const str = "Hello+Beautiful#World";
let counter = 1;
const result = str.replace(/[^\+#]+/g, m =>
`${m.trim()}${String(counter++).padStart(3, '0')}`
);
console.log(result);
Another option, which might not fit all cases, is to split before the special characters using a lookahead, map the items, and join with an empty string:
const str = "Hello+Beautiful#World";
let counter = 1;
const result = str.split(/(?=[+#])/)
.map(s => `${s.trim()}${String(counter++).padStart(3, '0')}`)
.join('')
console.log(result);

You could get the missing substrings by iterating the splitted value and check the parts.
var string = "Hello++#+Beautiful#World",
splitted = string.split(/[\+#]+/),
start = 0,
symbols = splitted.map((s, i, { [i + 1]: next }) => {
var index = string.indexOf(next, start += s.length);
if (index !== -1) {
var sub = string.slice(start, index);
start = index;
return sub;
}
return '';
});
console.log(symbols);
console.log(splitted.map((s, i) => s + symbols[i]).join(''));

My solution is to get the splitters then save them into an array and rejoin:
function splitAndRejoin(){
const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/);
var spliterCharacter = [];
for(var i = 0; i < str.length; i++){
if(str[i] == "+" || str[i] == "#"){
spliterCharacter.push(str[i]);
}
}
var rejoin = "";
for (i = 0; i <= spliterCharacter.length; i++) {
if(i< spliterCharacter.length)
rejoin += splited[i] + spliterCharacter[i];
else
rejoin += splited[i];
}
console.log(splited);
console.log(spliterCharacter);
console.log(rejoin); // Result
}

you can rejoin the array by finding the indexes that where the matching happened on the string
const str = "Hello+Beautiful#World";
const regex = /[\+#]/g;
const splited = str.split(regex);
console.log(splited);
//join
let x = '';
let i=0;
while ((match = regex.exec(str)) != null) {
x = x + splited[i] + "00" + (i+1) + str[match.index];
i++;
}
x = x + splited[splited.length-1] + "00" + (i+1);
console.log(x);

Related

Replace substring using for loop

I'm trying to replace a substring with the word 'denied'. For example: if the original string is "abcdefg" and sub-string to replace is "bcd", expected output is "aDENIEDefg".
I can't use .replace or anything else, just .substring
function replacer (variable, replace) {
for (let a = variable.length - 1; a >=0; a--) {
for (let b = replace.length - 1; b >= 0; b--) {
if (replace[b] === variable[a]) {
}
}
}
}
I have no clue what to do next.
Here is my code to just remove characters from a string.
let stringToReturn = original;
for (let a = toDelete.length - 1; a >= 0; a--) {
for (let b = original.length - 1; b >= 0; b--) {
if (original[b] === toDelete[a]) {
stringToReturn = stringToReturn.substring(0, b) + stringToReturn.substring(b + 1, stringToReturn.length);
} else {
continue;
}
}
}
alert(stringToReturn);
}
But this time I need not to just remove one characters, but find a sub-string to replace with DENIED. I apologize for the code style.
If you know the length of the substring you're trying to replace, then you can just iterate the string and examine all possible substrings of this length, as you were looking through a "window":
function replace(full, partial, placeholder) {
for (let i = 0; i <= full.length - partial.length; i++) {
const current = full.substring(i, i + partial.length);
if (current === partial) {
const prefix = full.substring(0, i);
const suffix = full.substring(i + partial.length);
return `${prefix}${placeholder}${suffix}`;
}
}
}
const ans = replace('abcdefghij', 'def', 'DENIED');
console.log(ans);
If you want to replace all occurrences, just don't return the value after the first match:
function replaceAll(full, partial, placeholder) {
let tmp = full;
for (let i = 0; i <= tmp.length - partial.length; i++) {
const current = tmp.substring(i, i + partial.length);
if (current === partial) {
const prefix = tmp.substring(0, i);
const suffix = tmp.substring(i + partial.length);
tmp = `${prefix}${placeholder}${suffix}`;
i += placeholder.length;
}
}
return tmp;
}
const ans = replaceAll('abcdefghijdef', 'def', 'DENIED');
console.log(ans);
Since you didn't specify whether you want to do a full replace or a singular, I've modified this to allow for a boolean parameter, this boolean says whether to do a singular or full replace.
const replaceword = "DENIED";
const testword = "abcdef";
const testword2 = "abcdefdexyz";
const testword3 = "hello I don't have the sub";
//function takes a word parameter - the word to do a replace on
//and sub parameter of what to replace
//and replacement parameter of what to replace the substring with
//replaceall is a boolean as to whether to do a full replace or singular
function replace(word, sub, replacement, replaceall){
replaceall = replaceall || false; //default to singular replace
//Get the first index of the sub to replace
const startOfReplace = word.indexOf(sub);
//get the ending index of where the substring to be replaced ends
const endOfReplace = startOfReplace + sub.length - 1;
//variable to hold new word after replace
let replacedWord = "";
//If the substring is found do the replacement with the given replacement word
if(startOfReplace > -1){
for(let i = 0; i < word.length; i++){
if(i == startOfReplace){
replacedWord += replacement;
}else if(i >= startOfReplace && i <= endOfReplace){
continue;
}else{
replacedWord += word[i];
}
}
}else{ //set the return to the passed in word as no replacement can be done
replacedWord = word;
return replacedWord;
}
if(replaceall) //if boolean is true, recursively call function to replace all occurrences
//recursive call if the word has the sub more than once
return replace(replacedWord, sub, replacement);
else
return replacedWord; //else do the singular replacement
}
console.log(replace(testword, "de", replaceword));
console.log(replace(testword2, "de", replaceword, true));
console.log(replace(testword3, "de", replaceword));
const source = "abcdefg";
const target = "bcd";
const replacer = "DENIED";
const replace = (source, target, replacer) => {
const position = source.indexOf(target);
if(position === -1) return source;
let output = source.substr(0, position)
output += replacer
output += source.substr(position + target.length);
return output
}
const replaceAll = (source, target, replacer) => {
let output = source;
do{
output = replace(output, target, replacer)
}
while(output !== replace(output, target, replacer))
return output;
}
console.log(replace(source, target, replacer))
and for sure best solution, easiest to understand, clean and elegant is :
const replaceAll = (source, target, replacer) => {
return source.split(target).join(replacer)
}

JavaScript: How to count repetitive letters in a string and output the numbers right after?

I am trying to display an output like this a3b2c4d3 for a string aaabbccccddd.
I tried the code below but didn't get the desired result.
var countLetters = "aaabbccccddd";
console.log("countLetters.length --->" + countLetters.length);
var countNumberLetter = 0;
var i;
var a;
for (i = 0; i < countLetters.length; i++) {
if (countLetters[i] == countLetters[i + 1]) {
countNumberLetter = countNumberLetter + 1;
}
}
console.log("countNumberLetter--------->" + countLetters[i] + countNumberLetter);
Use two loops. Use an outer while to loop the string. Whenever a new letter is encountered, use the for loop to increment count as the long as the letters belong to the same sequence. When done increment the outer counter (i) to get to the next letter:
var countLetters = "aaabbccccddd";
var result = '';
var i = 0;
while (i < countLetters.length) {
// iterate until current letter, and counted letter are not equal, increment count
for (var count = 1; countLetters[i] === countLetters[i + count]; count++) {}
// add current letter and count to string
result += countLetters[i] + count;
i += count; // increment outer counter - i
}
console.log(result);
Another solution that uses a String.match() with a regex to get an array of letter sequences. Then maps each sequence to letter + count, and joins them back to a string:
var countLetters = "aaabbccccddd";
var result = countLetters.match(/(\w)\1+/g) // match sequences of the same letter
.map((s) => s[0] + s.length) // map each sequence to letter with count
.join(''); // join back to a string
console.log(result);
var hashMap = {};
var countLetters = "aaabbccccddd";
countLetters.split("").forEach((letter) => {
if(!hashMap[letter]) {
hashMap[letter] = 0;
}
hashMap[letter] = hashMap[letter]+1;
})
var string ='';
for(var i in hashMap) {
var val = hashMap[i];
string += i + val;
}
console.log("countNumberLetter--------->",string);
const object = {};
const string = "aaabbccccddd";
// To iterate over string
for(let i = 0; i < string.length; i++){
// if the object has that alphabet just increment it
if(object.hasOwnProperty(string.charAt(i))){
++object[string.charAt(i)];
}else{
// else create a key to the new alphabet and give it a value 1
object[string.charAt(i)] = 1;
}
}
let finalString = "";
// To iterate over the object
for(let key in object){
finalString += key; // concatenate the key
finalString += object[key]; // concatenate the value
}
console.log(finalString);
My solution has two loops one to iterate over the string and store the alphabet and there count in an object ( you can use hashmap as well ).
The 2nd loop is to iterate over object so that we can make the desired string.

looping through a string and using repeat method

I'm trying to solve this exercise which goal is to give me a string that has to be turned into another string. The characters of the new string are repeated like in the example below.
Example:
accum("abcd"); // "A-Bb-Ccc-Dddd"
I wrote the following code:
function accum(s) {
counter = 0;
for (var i = 0; i < s.length; i++) {
return s[i].toUpperCase() + s[i].repeat(counter) + "-";
counter += 1;
}
}
When I try to run a sample test such as ZpglnRxqenU I get this error:
Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu', instead got: 'Z-'.
Apparently the problem is linked to the loop which is not working, but I can't figure out why.
Here's an ES6 one-liner :
const accum = word => word.toLowerCase().split("").map( (letter,index) => letter.toUpperCase() + letter.repeat(index) ).join("-")
console.log( accum("ZpglnRxqenU") )
Explanation :
word.split("") Start with breaking your string into an array of letters
.map( (letter,index) => Iterate each letter, keeping track of the index as you go
letter.toUpperCase() + letter.repeat(index) Replace each letter with the transformed value that you return
At this point, you have an array of transformed values
.join("-") Join everything back to a string with "-" as a separator.
You can combine the use of the methods: String.prototype.split(), Array.prototype.map() and Array.prototype.join():
function accum(s) {
return s
.split('')
.map(function (e, i) {
return e.toUpperCase() + e.repeat(i);
})
.join('-');
}
console.log(accum('ZpglnRxqenU'));
ES6:
const accum = s => s.split('').map((e, i) => e.toUpperCase() + e.repeat(i)).join('-');
console.log(accum('ZpglnRxqenU'));
You can do this:
function accum(s) {
s = s.toLowerCase();
const letters = [];
for (let i = 0; i < s.length; i++) {
letters.push(s[i].toUpperCase() + s[i].repeat(i));
}
return letters.join('-');
}
console.log(accum('ZpglnRxqenU'));
You have an array and fill it with the letters, once filled you join the elements with '-'. You could just add the letters to a string but at the end you would have to trim the trailing '-', which isn't wrong but now you have 2 ways to do this.
Also you don't need the counter variable because i is already counting.
With array.reduce:
var str = "abcd";
function accum(str) {
var arr = str.split("");
return arr.reduce((m, o, i) => {
m += (i === 0 ? "" : "-") + o.toUpperCase() ;
for (var k = 0; k < i; k++) {
m += o;
}
return m;
}, "");
}
var ret = accum(str);
console.log(ret);
This should work for you. When you return the loop will stop. You need to remove that.
function accum(s) {
counter = 0;
sA = s.split('');
for (var i = 0; i < s.length; i++) {
sA[i] = sA[i].toUpperCase() + sA[i].toLowerCase().repeat(counter);
counter += 1;
}
return sA.join('-');
}
console.log(accum('ZpglnRxqenU'));

How can i split a string into words without split function in javascript

How can I split string into words without using split function in javascript. I wonder for a little help.
this is my code:
function trocearCadena(cadena) {
var posEspacios = buscarEspacios(cadena);
var palabras = [];
var j = 0;
while (true) {
var pos = posEspacios.shift();
var subcad = (j == 0) ? cadena.substring(0, pos) : cadena.substring(j + 1, pos);
palabras.push(subcad);
j += pos;
if (j > cadena.length) {
var ultpal = cadena.substring(pos + 1);
palabras.push(ultpal);
break;
}
}
return palabras;
}
function buscarEspacios(cadena) {
var espacios = [];
var pos = -1;
do{
pos = cadena.indexOf(" ", ++pos);
if (pos != -1) espacios.push(pos);
} while (pos != -1);
return espacios;
}
I don't understand what your variable names mean, so I wasn't able to fix the code. Here's another one:
str = "How can I split string into words without using split function in javascript."
var words = [""];
for(var i = 0; i < str.length; i++)
if(str[i] !== " ")
words[words.length - 1] += str[i];
else if(words[words.length - 1])
words.push("");
document.write(words)
Assuming that you also can't use what #Oriol suggested, I would use a recursive function like in the following example:
function _split(s, arr) {
var
str = s.trim(),
words = arr || [],
i = str.indexOf(' ');
if(i !== -1) {
words.push(str.substr(0, i)); // collect the next word
return _split(str.slice(i + 1), words); // recur with new string and words array to keep collecting
} else {
words.push(str); // collect the last word
return words;
}
}
Usage:
_split(' one two three ');
//=> ["one", "two", "three"]

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.

Categories