javaScript change string char's position - javascript

Let's say i have three variables:
a, b, c
and i set them such values:
2,1,3
I have such string:
ilovemama
how could i change char position, via block's of three, in my case i have three blocks:
ilo
vem
ama
let's try on first block:
1 2 3
i l o
and i must change this position's via my a,b,c:
2 1 3
l i o
And so over, and then concat this block's into one line...
I think that i explain it normally.
I can do this on jQuery, but i can't imagine, how to do this on pure JS. i try a little bit, but this is without sense(

var string = 'some string'
a = string.charAt(0),
b = string.charAt(1),
c = string.charAt(2); // and so on
var newString = b + a + c; //oms
var otherString = c + b + a; //mos
.charAt(0) will select the first leter of the string(the one with index 0) and so on.
assigning the values to vars you can manipulate the string as I understand you want to do
for blocks,
doing;
var string='some string';
var a = string.slice(0, 3),
b = string.slice(3, 7),
c = string.slice(7, 11); and so on
Then the same
var newString = c +a +b; // will be = 'ringsome st'
To find an Index as you request in the comment you can use;
var str = "Hello There",
indexOfr = str.indexOf("r");
console.log(indexOfr); // outputs 9
A function could be;
function dynamo(string) {
var len = string.length-1,
parts = 3,
whereToCut = Math.floor(len/parts);
var a = string.slice(0, whereToCut),
b = string.slice(whereToCut, (whereToCut *2)),
c = string.slice((whereToCut *2), len+1);
return b + a + c;
//(or you could hwere some code to see what order you want, i dont understand your request there)
}
dynamo('what do you really want to do??');
//returns "u really wwhat do yoant to do??"

Related

Code to get incremental excel column name in JavaScript

I want to create a loop which increments the column name of excel from a starting point.
For Example:
If I start the column name from X so as long as I keep increment the character by 1 It should return the output like - Y, Z, AA, AB,..., AZ, BA, BB,... .
The starting of Excel column name is A and code should be able to return the column name with atleast 5 characters i.e. ZZZZZ, untill loop continues.
This is what I tried, but can't handle for increasing column name after Z:
var i3;
var text3 = "";
var c;
for(i3 = 65; 90 >= i3; i3++) {
c = String.fromCharCode(i3);
text3 += c + ", ";
}
Haven't done any javascript in several years so this is purely logic-based.
Could have a while loop going which calculates the MOD(i3Check,26)>0 with MOD being function to check what the remaining is of i3Check/26, i.e. 27/26 = 1
Something like this in your for loop (don't forget var i3Check):
c = ""
i3Check = i3
While(MOD(i3Check,26)>0){
c = c+String.fromCharCode(26);
i3Check = i3Check - 26;
}
If(i3Check>0){
c = String.fromCharCode(i3Check) + c;
}
I have no way to test this nor do I know the syntax anymore for javascript but it should be close :p

Designing a custom file number string based on input

I really need your help with this since this goes well beyond my level of capability of javascript coding.
I'd like to design a function that would accomplish one of the following two scenarios:
If there is no dash and number at the end of the string var 'fileno', then rewrite the string fileno and add the dash and then the count at the end.
var fileno = 'test'
var c = 4
fileno = 'test-4'
If there is already a dash and then a number at the end of the string, replace the dash-number with the new info below:
var fileno = 'test-2'
var c = 3
fileno = 'test-3'
You may use regular expression with String.prototype.replace():
fileno = fileno.replace(/-\d+$|$/, '-' + c);
It literally means: replace -{number} or nothing at the end of the string with -{c}.
var c = 3;
console.log( 'test'.replace(/-\d+$|$/, '-' + c) );
console.log( 'test-4'.replace(/-\d+$|$/, '-' + c) );
if(fileno[fileno.length - 2] === "-"){
fileno = fileno.substr(0,-1) + c;
} else {
fileno += "-" + c;
}
Just either append a new number if there is already a - in the second last position or append a new one.

Using character codes to get frequency on words in a string, JavaScript

I'm trying to rewrite this frequency finding program in Javascript. Here is the Java code:
public class frequency {
public static void main(String[] args){
String S = "Temple University";
int[] p = new int[256];
for (char c :S.toCharArray()) {
p[c]++;
System.out.println(c +" shows up "+p[c] + " times");
}
Output:
T shows up 1 times
e shows up 1 times
m shows up 1 times
p shows up 1 times
l shows up 1 times
e shows up 2 times
shows up 1 times
U shows up 1 times
n shows up 1 times
i shows up 1 times
v shows up 1 times
e shows up 3 times
r shows up 1 times
s shows up 1 times
i shows up 2 times
t shows up 1 times
y shows up 1 times
However, my JavaScript implementation doesn't work at all:
function frequency(){
s = "Temple University";
str = s.split('');
p = [];
p.length = 256;
console.log("start");
for(c in str){
p[c]++;
console.log("inside" + c);
console.log(String.fromCharCode(c) + " shows up " + p[c] + "times");
}
}
It's late I've been trying to figure out why this JavaScript code is not working so I'm sorry if this post seems unpolished.
You can manipulate string directly as array and need a safe check for occurrence of chars else assign value 1.
So use a for loop for iterating over whole string can extract char as s[index] while using p[char] for occurrence frequency.
sample code follows
function frequency(){
s = "Temple University";
p = [];
console.log("start");
for(var i=0;i<s.length;i++){
if(!p[s[i]]){
p[s[i]] = 1;
}else{
p[s[i]]++;
}
console.log(s[i] + " shows up " + p[s[i]] + "times");
}
}
frequency()
Does this work for you? If so, you just weren't referencing the charCode but the index of the letter in the string..
function frequency() {
s = "Temple University";
str = s.split('');
p = [];
p.length = 256;
console.log("start");
for (c in str) {
var curChar = str[c];
var charCode = curChar.charCodeAt();
p[charCode] ? p[charCode]++ : p[charCode] = 1;
console.log(curChar + " shows up " + p[charCode] + " time(s)");
}
}
frequency()
The main reason this isn't working is that for loops work differently in Javascript than in Java. In Javascript, a for-in loop iterates through the properties of an object, not the indices of an array or string, so rather than for-in, you'd want to use a plain for loop, like so:
function getFrequencies(string) {
if (typeof(string) !== 'string') {
throw new Error('string argument is not of type string.');
}
var str = string.split('');
var frequencies = {};
for (var c = 0; c < str.length; c++) {
var charCode = String.fromCharCode(str[c]);
if (!frequencies[charCode]) {
frequencies[charCode] = 1;
} else {
frequencies[charCode]++;
}
}
return frequencies;
}
A couple tips: you would want to use a plain object ({}) instead of an array ([]), given that you're counting unique values. Secondly, there's no need to declare the length of an array in Javascript -- arrays are automatically resized as they grow, and the length property is readonly anyway.
You may do as follows;
var s = "Temple University",
fmap = Array.prototype.reduce.call(s,(p,c) => (p[c] ? p[c]++ : p[c] = 1,p),{});
for(var i in fmap) console.log(i, "shows up", fmap[i],"times.");
We are using an array functor Array.prototype.reduce() over a string by using a Function method .call(). So the first argument passed to .call() is the string s itself (designating the context to be called upon) and a callback ((p,c) => (p[c] ? p[c]++ : p[c] = 1,p)) for the second argument to be invoked per item (character) of the string. The .reduce() functor uses an empty object {} as an initial value which will be assigned to p, whereas c would be assigned to the first character in the first turn. It will generate a map called fmap like;
{ T: 1,
e: 3,
m: 1,
p: 1,
l: 1,
' ': 1,
U: 1,
n: 1,
i: 2,
v: 1,
r: 1,
s: 1,
t: 1,
y: 1 }
Then a for in loop traverses over the map keys and we display the obtained data by a console.log() instruction.

Using Heron's formula to calculate area - JavaScript

My code:
function calculate(sides) {
var sides = prompt("Triangle side lengths in cm
(number,number,number)"); //String will be size of 4
var nsides = sides.split(" "); //Splits content into array format
//Convert Array instances to integer values a,b,c
for(var loop=0;loop<=nsides.length;loop++) {
if(nsides[loop]!=",")
a = nsides[loop];
if(nsides[loop]!=",")
b = nsides[loop];
if(nsides[loop]!=",")
c= nsides[loop];
} //End for
//Area Calculation
var s = (a+b+c)*0.5 ; //represents the semiperimeter
var area = Math.sqrt(s*(s-a)*s(s-b)*(s-c)) //area calculation
//Result
sides = alert("The triangle's area is " + area + " square cm");
} //End function
//Main calculate(length);
I'm looking to set side a, b, and c to integers; however in order to do that I have to go through the array (I first converted it to an array from a string)
I'm going to add in some standard validation later; as of now I can't seem to place the values from the string entered into 3 separate integers being a b and c.
Other than that, is there a better way i can go about this?
Thanks.
Maybe I misunderstand your question, but is this what you're looking for?
var sides = prompt("Triangle side lengths in cm (number,number,number)");
var nsides = sides.split(",");
var a = +nsides[0];
var b = +nsides[1];
var c = +nsides[2];
//Area Calculation
//...
Note the use of + to force the strings from the array into numbers.
function calculate() {
var sides = prompt("Triangle side lengths in cm (number,number,number)"),
nsides = sides.split(","),
a = parseFloat(nsides[0]),
b = parseFloat(nsides[1]),
c = parseFloat(nsides[2]),
s = (a + b + c) / 2,
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
alert("The triangle's area is " + area + " square cm");
return area; // return the area
}
First of all I removed your parameter, it was totally unnecessary and was overwritten by the declaration of sides in the first line. Then I changed the split to , so it follows your instructions. Then you need to parse the string to integers using parseInt and specifiying the radix 10, then you can go on with your calculations. Just a last thing, you wrote Math.sqrt(s*(s-a)*s(s-b)*(s-c)), see that s(s-b) causes an exception because you are using a number to be called as a function.

how to prevent chain when adding javascript variables containing numbers

How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.

Categories