how to reverse string without using any built in functions in javascript - javascript

can anyone please tell me how to reverse a given string without using ANY built in functions?
I have tried following ones, but in all cases there is some built in functions involved
function reverseString(str){
return str.split("").reverse().join("");
}
reverseString("I love coding");
function reverseString(str){
var myArray = [];
for(var i = 0; i <= str.length; i++ ){
myArray.push(str.charAt(str.length - i));
}
return myArray.join("");
}
reverseString("I love coding");
function reverseString(str){
var reversedString = '';
for(var i = str.length -1 ; i >= 0; i--){
reversedString += str[i];
}
return reversedString;
}
reverseString("I love coding");
function reverseString(str){
var newArray = [];
for(var i = str.length -1, j = 0; i >= 0; i--, j++){
newArray[j] = str[i];
}
return newArray.join("");
}
reverseString("I love coding");

to comply with requirement of no natives and no var declaration I've cheated.
named arguments can be reassigned.
var s = 'foobar';
function r(e,v,r){
for(r=e.length,v='';r;)v+=e[--r];return v;
}
console.log(r(s));

It is very simple
var name = 'bhaurao';
var newName = '';
for(i in name){
newName = name[i] + newName;
}
console.log("reverse string is "+newName);
You can check example here Click here

Related

Javascript to generate dynamic string of numbers

I have a requirement to write a function to generate the below dynamic string.
Here are some examples of what the output should look like for a function argument of 6, 5, and 4, respectively (Actually I am flexible with passing the argument).
123456789112345678921234567893123456789412345678951234567896
12345678911234567892123456789312345678941234567895
1234567891123456789212345678931234567894
The length of the output will always be a multiple of 10.
Should I use normal JS arrays OR can I use some ready jQuery methods to acheive this ?
Here is the code, I think it will help you
function dynamicNumber(n){
var s="";
for(i=1;i<=n;i++){
s=s+"123456789"+i;
}
return s;
}
Try something like this.
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
Example below:
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
console.log(generateString(6))
console.log(generateString(5))
console.log(generateString(4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is how I do it:
function dynamic_string(val){
var strin = "123456789"
var result = ""
for(var i = 1; i <= val; i++){
result += strin;
result += i;
}
console.log(result)
}
dynamic_string(6)
What about (ES6):
function getString(amount) {
let sNumber = '';
for(let i=1;i<=amount;i++) {
sNumber += '123456789' + i;
}
return sNumber;
}
Try this way
var nu=5;
for(var i=1;i<=nu;i++){
for(j=1;j<=9;j++){
console.log(j)
}
console.log(i)
}
jsbin
You can use this simple logic...
var str = '123456789';
var len=5;
var out = ''
for(var i=1;i<=len;i++){out+=str+i;}
console.log(out)

How to do a reverse-word function in Javascript

I'm trying to do a reverse-word script in javascript. I have written this function, but it does not work and I can't understand why. What is wrong? Is there any other way to do it?
function inverser(x)
{
var newString ="";
var index=(x.length - 1);
var y=0;
for (var i=index ; i>=0 ; i--)
{
x[i] = newString [y++];
}
return (newString );
}
console.log(inverser("test"));
You need to add to concatenate newString instead of trying to assign an index to it. The logic of your function should be
newString[y++] += x[i];
Link to code
when you use newString[y++], newString is still empty string and doesn't have cell 1 or 2 or 3 .... and can't assign string to this cell.
simply if you remove y variable and make some move on line 9 can get answer.
here the code worked for me:
function inverser(x) {
var newString = "";
var index = (x.length - 1);
for (var i = index; i >= 0; i--)
{
newString += x[i];
}
return (newString);
}
Use reverse():
function inverser(x)
{
return x.split("").reverse().join("");
}
It's simple if you don't need build in function, please comment, i will update my answer :)
Update
The assignment statements are wrong in your code, it should have been:
newString += x[i];
"use strict";
function wordReverse() {
const str1 = "God is Good";
const str2 = str1.split(" ");
//console.log(str2);
const reverseWord = [];
const len = str2.length;
//console.log(len);
for (let i = len - 1; i >= 0; i--) {
reverseWord.push(str2[i]);
}
return reverseWord;
}
console.log(wordReverse().join(" "));
const word = "reverse";
const reverseString = (str) => str.split("").reverse().join("");
reverseString(word);
function reverseWord(str) {
const splittedString = str.split(" ");
const wordreverse = [];
const len = splittedString.length;
for (let i = len - 1; i >= 0; i--) {
wordreverse.push(splittedString[i]);
}
return wordreverse.join(" ");
}
function reverseWord(str) {
const splittedString = str.split(" ");
const wordreverse = [];
const len = splittedString.length;
for (let i = len - 1; i >= 0; i--) {
wordreverse.push(splittedString[i]);
}
return wordreverse.join(" ");
}
console.log(reverseWord("hello world"))

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

Getting a nth element from a string

How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {

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