ok I want do have a jscript below
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
if($.inArray(i,arr)){
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
and you may see it running here
http://jsfiddle.net/laupkram/WfUUp/
now what I want there is to provide a subject string and an array.
the subject string is the string to be process and the array contains numerical values that will represent the character index in the string to uppercase.
did i miss something with my script that's why I get undersirable results?
Check the docs for $.inArray . It returns the index of the element that was found or -1 if not found.
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
//CHANGE HERE
if($.inArray(i,arr) != -1){
//^^ change this
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
$(document).ready(function() {
var str = 'post'; //the subject string
var arr = [0, 2]; //to uppercase character index 0 and 2
str = str.split("");
for (var i = 0; i < arr.length; i++) {
if (str[arr[i]]) {
str[arr[i]] = str[arr[i]].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
2 Things that I see wrong here:
No need to split the str, you can loop over it normally.
You got inArray() wrongly. The below snippet from jquery api for inArray
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when > it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
So, as inArray is returning -1 for indexes that it didn't find, you if statement is becoming true, and hence you are getting the result as 'PoST'.
I would re-write this as
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(i = 0; i < arr.length; i++){
str[arr[i]]=str[arr[i]].toUpperCase();
}
str = str.join('');
alert(str);
http://jsfiddle.net/NBBgz/
Related
I am trying to code the Hill cipher, which assigns each letter of the alphabet with a number, starting from 0. So A = 0 and Z = 25. With what I have so far, it correctly makes this numeric alphabet but when I insert K as the message to encrypt to its assigned number, the output is 1, and not 10. So if I type in KLM, the output is 101. I pretty sure I need to fix the second for loop.
var plainAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var cipherAlphabet = '';
for(var i = 0; i < plainAlphabet.length; i++){
var letter = plainAlphabet.charAt(i);//getting the character
var index = plainAlphabet.indexOf(letter);
letter = index;
cipherAlphabet += letter;
}
var encryptedMsg = '';
for(var i = 0; i < msg.length; i++){
var letter = msg.charAt(i);
var index = plainAlphabet.indexOf(letter);
encryptedMsg += cipherAlphabet.charAt(index);
}
The error is coming from the fact that cipherAlphabet.charAt(index) will return THE only char at the index indicated. So if will give you 1 because it is the first char of 10.
Here is a functional code:
msg = ""
var encryptedMsg = '';
for(var i = 0; i < msg.length; i++){
var letter = msg.charAt(i); // (1)
let cipher = letter.charCodeAt(0)-65 // (2)
encryptedMsg += cipher;
}
Explanation :
(1) You get the char at the given index
(2) You are getting the ASCII code of the letter and you subtract it from the A ASCII code (65).
I think that this is the shortest way to make it work.
If you want to continue on what you have done, you can transform var cipherAlphabet = '' into an array var cipherAlphabet = [] and then, access the element of the array. So you would replace your last ligne encryptedMsg += cipherAlphabet[i].
Note that to add an element to an array, you have to use cipherAlphabet.push(element)
I am trying to reassign a value at x index in a multidimensional array, and I get the error in the title. Here is my code:
var str = "SERR PBQR PNZC";
var arr = str.split(" ");
for(var i = 0; i<arr.length;i++){
for(var j=0; j<arr[i].length;j++){
arr[i][j] = String.charCodeAt((arr[i][j]) - 13);
}
}
Any help is appreciated thanks! My apologies for lack of information the first time, i am scatterbrained at this point
An assignment to a multi-dimensional array is not happening. An assignment to a string at a specific index is happening. Strings are immutable—they can't be assigned to—so you can't do that.
Basically what's happening is the following:
var arr = "SERR PBQR PNZC".split(" ");
var str = arr[0]; // "SERR", this is a string
str[0] = "o"; // doesn't work, can't assign to string at an index
You'll need to change your code with that in mind. Perhaps you meant to work with the numbers array?
You probably want this:
var str = "Hello World";
var arr = str.split(" ");
var numbers = [];
for (var i = 0; i < arr.length; i++) {
numbers[i] = [];
for (var j = 0; j < arr[i].length; j++) {
numbers[i][j] = arr[i].charCodeAt(j) - 13;
}
}
console.log(numbers);
String.charCodeAt() is a method on Strings, not a stand-alone utility function. You want arr[i].charCodeAt(j) or even arr[i][j].charCodeAt() (because it returns the character code of a single character).
Also, you need to fix your parenthesis - you're trying to subtract 13 from string rather than subtracting 13 from your character code.
I am learning JavaScript and I am disappointed that the below code doesn't work. It is still a lowercase "i". I was trying to capitalize every letter in the string (hence the for loop) but I wanted to stop and address what was going wrong.
str = 'i ran there';
for(var i = 0; i<str.length; i++){
if(i===0){
str[i] = str[i].charAt(0).toUpperCase();
}
}
console.log(str);
Can someone please describe what is going wrong here?
whats going wrong here is strings in javascript are immutable.
You can't change them. What you can do is create a new string with the change.
If I understand your question, you could do it with something like -
var str = 'i ran there';
var arr = str.split(" ");
var div = document.getElementById("out");
for(var i = 0; i < arr.length; i++){
// The First letter
// arr[i] = arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
// Every letter
arr[i] = arr[i].toUpperCase();
div.innerHTML += arr[i] + "<br />";
}
<div id="out"></div>
As for what is going on in your code, you can't modify the array backing the String (assuming it is an array) like that.
You are asking for index i of a String str. Because str is a String, you cannot use index values to grab certain characters in the string - try console.log(str[0]) - it will return undefined.
To accomplish what you are trying to do, you would need to simply add to a new string after capitalizing each letter. Example:
str = 'i ran there';
capStr = ''
for(var i = 0; i < str.length; i++){
if(i === 0) capStr += str.charAt(i).toUpperCase();
else capStr += str.charAt(i);
}
console.log(capStr);
You have to create a new string because strings in javascript are immutable:
First get every word separated:
var arrayOfstrings = s.split(" ");
Then you can treat each string like there own word
Fancy way :
var capFirstLetter = arrayOfStrings[index].replace(/^./, function (match) {
return match.toUpperCase();
});
Which is just a regex. The /^./ means the first character in the string. And the rest is self explanatory.
Or this way:
var s = arrayOfStrings[index];
var s2 = s[0].toUpperCase()+ s.substr(0,1);
Or even this really lame way
var s = arrayOfStrings[index];
var newS = "";
for(var i = 0; i < s.length; i++){
if(i == 0) newS+= s[0].toUpperCase();
else newS+= s[i];
}
Of course all these can be done in a forloop to cap them all and put back together:
var s = "hello woorld hello world";
var arrayOfStrings = s.split(" ");
for(var i = 0; i < arrayOfStrings.length; i++){
arrayOfStrings[i]= arrayOfStrings[i].replace(/^./, function(match) {return match.toUpperCase();});
}
var s2 = arrayOfStrings.join(" ");
I would like to turn "one,two,three,four,five" into "$one $two $three $four $five".
Here is what I have so far to separate/explode the comma-separated list.
var str = 'one,two,three,four,five';
var str_array = str.split(',');
for(var i = 0; i < str_array.length; i++)
{
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
}
How can I prepend a character to each value and out them as space-separated list?
It would be great to turn the code into a function that can be applied to a string.
It is as simple as:
'$' + ('one,two,three,four,five'.split(',').join(' $'))
Here is a function that will do it, and output an empty string if there is no matches:
function (s) {
var a = s.split(',').join(' $');
return a ? '$' + a : '';
}
Use the + operator and join:
for(var i = 0; i < str_array.length; i++) {
str_array[i] = 'a' + str_array[i];
}
var out_str = str_array.join(' ');
Replace 'a' with whatever character you wish to prepend.
Also we can use replace()
var str = 'one,two,three,four,five';
var str_array = str.split(',');
for (var i = 0; i < str_array.length; i++) {
str = str.replace(',', '$');
}
alert('$' + str);
i am trying to create a program that stores words in an Array, what I've done is whatever the program finds a separator (" " or ",") it pushes it in the array, my problem here is that it store even the separators with it (i must use the array SEPARATORS).
var sentence = prompt("");
var tab = [];
var word = "" ;
var separators = [" ", ","];
for(var i = 0 ; i< sentence.length ; i++){
for(var j = 0 ; j < separators.length ; j++){
if(sentence.charAt(i) != separators[j] && j == separators.length-1){
word += sentence.charAt(i);
}else if(sentence.charAt(i) == separators[j]){
tab.push(word);
word = "";
}
}
}
tab.push(word);
console.log(tab);
You can try this:
var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);
If you don't want empty strings:
var words = text.split(/,|\s/).filter(function (e) {
return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]
If you need to use the array you can try this:
var text = 'Some test sentence, and a long sentence',
s = [',', ' '],
r = RegExp('[' + s.join('') + ']+'),
words = text.split(r);
I would just use regex:
var words = sentence.split(/[, ]+/);
If you want to fix your code, use indexOf instead of a for loop:
for (var i = 0; i < sentence.length; i++) {
if (separators.indexOf(sentence.charAt(i)) === -1) {
word += sentence.charAt(i);
} else {
tab.push(word);
word = "";
}
}
After reexamining the problem, I think you need a combination of native string functions and the compact method from the excellent underscore library which removes 'falsy' entries in an array:
$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
words = [];
var string = $('#textfield).val()
//replace commas with spaces
string = string.split(',').join(' ');
//split the string on spaces
words = string.split(' ');
//remove the empty blocks using underscore compact
_.compact(words);
}