“str.fromCharCode is not a function” - javascript

Im getting the following errors:
str.fromCharCode is not a function
newStr.push is not a function
I have no clue why I’m getting those errors tbh. I might be using methods the wrong way
function rot13(str) {
var newStr = str;
for (i = 0; i < str.length; i++) {
str.fromCharCode(str[i] - 13);
newStr.push(i);
}
return newStr;
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)

You could try something like:
function rot13(str) {
var newStr = [];
for(i = 0; i < str.length; i++){
let x = String.fromCharCode(str[i].charCodeAt()-13);
newStr.push(x);
}
return newStr.join("");
}

It is String.fromCharCode, not myString.fromCharCode
Lastly you want charCodeAt to subtract from
Also you cannot push a char to a string. push is an Array method
function rot13(str) {
var newStr = []; // using an array - you can use += to concatenate to string
for (i = 0; i < str.length; i++) {
// I suggest you do not convert the space.
// Here I converted it to another type of space but you can use " " if you want
var x = str[i] == " " ? "\u2005":String.fromCharCode(str[i].charCodeAt(0) - 13);
newStr.push(x);
}
return newStr.join("");
}
// Change the inputs below to test
console.log(
rot13("SERR PBQR PNZC")
)

Related

How can I extract all contained characters in a String? [duplicate]

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)

Javascript: I am trying to loop through a string of characters and determine if a character is missing

this is my challenge: Create a function that will find the missing letter passed in the parameter and return it. If all letters are present in the string, the return will be undefined. For example missingLetter("abce") should return "d", missingLetter("bcd") should return undefined.
I am having trouble with this one, can you please tell me if I am on the right track with my code:
var missingLetter = function(char){
var missing = "";
var str = "abcdefghijklmnopqrstuvwxyz";
for (var i = char[0]; i < char.length; i++){
for(var y = char[0].indexOf(str); y < char.length; y++ ){
if(char[y].indexOf(str) == -1 ){
missing.push(char[y]);
}
}
}
console.log(missing);
return missing;
}
missingLetter("abce")
Tonmoy already give the answer if you want you can check this. First if you want to use push function then you must create a array.
var missingLetter = function(char){
var missing = []
var y = 0
var str = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < str.length; i++){
while(y < char.length ){
if( char[y] != str[y+i] ){
missing.push(str[y+i])
++i
}
else
++y
}
}
console.log(missing)
return missing
}
missingLetter("cdz")
you have defined variable missing as string, but It should be a array(). The loop condition is not properly. Following is the code snippet, which works fine.
var missingLetter = function(char){
var missing = new Array();
var str = "abcdefghijklmnopqrstuvwxyz";
var i = 0;
while(i<char.length) {
for(var j=0;j<26;j++) {
if(str[j].indexOf(char[i])>-1){
i++;
} else {
missing.push(str[j]);
}
}
}
console.log(missing);
return missing;
}
missingLetter("abce");

String.fromCharCode gives no result javaScript

after running code i get no result in window. and i cant find problem
result have to be string created from charCode.
function rot13(str) {
var te = [];
var i = 0;
var a = 0;
var newte = [];
while (i < str.length) {
te[i] = str.charCodeAt(i);
i++;
}
while (a != te.length) {
if (te[a] < 65) {
newte[a] = te[a] + 13;
} else
newte[a] = te[a];
a++;
}
var mystring = String.fromCharCode(newte);
return mystring;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
The method String.fromCharCode expects you to pass each number as an individual argument. In your code sample, you are passing an array as a single argument, which won't work.
Try using the apply() method instead, which will allow you to pass an array, and it will convert that into multiple individual arguments:
var mystring = String.fromCharCode.apply(null, newte);
Looks like String.fromCharCode() is not defined to operate on an array.
Try like this:
function rot13(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i) + 1;
if (charCode < 65) {
charCode += 13;
}
result += String.fromCharCode(charCode);
}
return result;
}
// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC"));
NOTE: I copied your logic for the character substitution, but it doesn't seem correct.

Javascript Learnstreet Email Interpreter Alternative Solution

So I was doing this assignment on Learnstreet and for those of you who want to read a little on the question here's the link:
http://www.learnstreet.com/cg/simple/project/email_interpret#check
Long story short - you're given a email string like "local#domain.com" and you're expected to return a 2 member array that would look like ["local","domain"]. So I wrote this and am wondering how this is not correct.
function extractLocalDomain(str)
{
var text = str.trim(); //eliminates leading and trailing spaces
for(var i = 0; i < text.length; i++) {
if(text[i] == "#") {
var local = text.slice(0, i-1);
var domain = text.slice(i+1)
return [local,domain];
}
i++
}
}
You are incrementing i twice:
function extractLocalDomain(str) {
var text = str.trim();
for (var i = 0; i < text.length; i++) { // <- increment here
if (text[i] == "#") {
var local = text.slice(0, i - 1);
var domain = text.slice(i + 1)
return [local, domain];
}
i++ // <- and here agin, remove this
}
}
Instead of using a loop, you can also just use .indexOf.

how to extract numbers from string using Javascript?

how to extract numbers from string using Javascript?
Test cases below:
string s = 1AA11111
string s1= 2111CA2
string s result = 111111
string s1 result = 211112
My code below is not working:
var j = 0;
var startPlateNums = "";
while (j <= iStartLength && !isNaN(iStartNumber.substring(j, j + 1))){
startPlateNums = startPlateNums + iStartNumber.substring(j, j + 1);
j++;
}
How about a simple regexp
s.replace(/[^\d]/g, '')
or as stated in the comments
s.replace(/\D/g, '')
http://jsfiddle.net/2mguE/
You could do:
EDITED:
var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]
A regex replace would probably the easiest and best way to do it:
'2111CA2'.replace(/\D/g, '');
However here's another alternative without using regular expressions:
var s = [].filter.call('2111CA2', function (char) {
return !isNaN(+char);
}).join('');
Or with a simple for loop:
var input = '2111CA2',
i = 0,
len = input.length,
nums = [],
num;
for (; i < len; i++) {
num = +input[i];
!isNaN(num) && nums.push(num);
}
console.log(nums.join(''));

Categories

Resources