Javascript breaking up string and reverse it - javascript

I am trying to figure out how to break up a sting to groups of five and reverse each one individually. I want it to work for any string, (there is no delimiter for splitting)
For example, if the variable is:
Iwanttobreakthisintogroupsoffiveandreverse
I would want it to return:
tnawI erbot ihtka otnis puorg iffos dnaev rever es
How do I go about this?

var str = "Iwanttobreakthisintogroupsoffiveandreverse"
var result = [];
str.replace(/.{1,5}/g, function(m) {
result.push(m.split('').reverse().join(''));
});
result.join(' ');
// "tnawI erbot ihtka otnis puorg iffos dnaev rever es"

var input="Iwanttobreakthisintogroupsoffiveandreverse";
var matches = input.match(/.{1,5}/g);
for (i = 0; i < matches.length; ++i) {
matches[i] = matches[i].split("").reverse().join("");
}
alert(matches);
It pops up tnawI,erbot,ihtka,otnis,puorg,iffos,dnaev,rever,es

You could try this:
var chars = "Iwanttobreakthisintogroupsoffiveandreverse".split('')
var str_rev = []
for (i = 0; i < chars.length; i += 5)
str_rev.push( chars.slice(i, i + 5).reverse().join('') )
Convert to char array using split(''). This allows you to use array methods like reverse and slice
Loop through the char array taking 5 element slices
reverse the elements, join the chars to create a string, and add it to rev_str

Related

How to make element in Array change its' place

I'm beginner in JS. I've tried to understand Caesar Cipher ROT13, but it was too complicated for me. So I've tried to write my own code. Here it is below:
function encrip() {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = "Ni Hao";
var string = str.toUpperCase();
for (var i = 0; i < string.length; i++) {
for (var k = 0; k < alphabet.length; k++) {
if(string.charAt(i) == alphabet[k]) {
/* console.log(string.charAt(i) + ' ' + alphabet.indexOf(alphabet[k])); */
}
}
}
}
encrip();
But I am stuck. How to do:
1. Get value from var str and then access to var alphabet , after change each letter from var str value to next 3 from alphabet (var str each element's current position would be changed) For example: Input: Ni Hao ==> output: QL KDR
2. Create universal code, I mean, not only for changing position by 3, but when I give value '5', each element would be changed by next 5 positions from alphabet. So output can be changed when I change its' value
I hope I explained everything clearly. Thanks everyone in advance for help!!
you can use the following function to encrypt english words, the 1st parameter is the string to encrypt and the 2nd for shifting
function encryp(str,pos){
var alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strUC=str.toUpperCase();
var enc="";
for(var i=0;i<strUC.length;i++){
if(strUC.charAt(i)!=" "){
enc+=alpha.charAt((alpha.indexOf(strUC.charAt(i))+pos)%26)
}
else{
enc+=" "
}
// in your case pos=3
}
return enc;
}
console.log(encryp("NiHao",3));
You don't need two for loops to do this. Iterate over the input string and find the index of each character in the alphabet array, if found add the shift to it to get the encrypted character.
To handle overflow use the modulus operator to cycle through the array.
Also I assume that you are not going use any special symbols to do the encryption.
function encrip(string, shift) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
string = string.toUpperCase();
let arr = [];
for (var i = 0; i < string.length; i++) {
let char = alphabet.indexOf(string[i]) !== -1 ? alphabet[(alphabet.indexOf(string[i]) %26) + shift] : " ";
arr.push(char);
}
let encryp = arr.join("");
console.log(encryp);
return encryp;
}
encrip("Ni Hao", 3);
First of all, instead of your inner for loop scanning the whole alphabet array, you can use the built-in function indexOf:
alphabet.indexOf('K') // returns 10
Secondly, you'll want to build up your enciphered string in a separate variable. For each letter, get the index of that letter in the alphabet, add your cipher offset parameter to that index and add the resulting letter from the alphabet to your new string. An important step is that when you add to the index of the letter, you want to make sure the resulting index is within range for the alphabet array. You can do that using the % (modulo) operator, which will wrap high values back round to the start of the array. In full:
function encipher(input, offset) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = input.toUpperCase();
var result = '';
for (var i = 0; i < str.length; i++) {
letterIndex = alphabet.indexOf(str.charAt(i));
if (letterIndex === -1) {
result += str[i]; // if the letter isn't found in the alphabet, add it to the result unchanged
continue;
}
cipheredIndex = (letterIndex + offset) % alphabet.length; // wrap index to length of alphabet
result += alphabet[cipheredIndex];
}
console.log(result);
}
encipher('Ni Hao', 5); // output: 'SN MFT'

put dash after every n character during input from keyboard

$('.creditCardText').keyup(function() {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
}
$(this).val(foo);
});
I found this tutorial on putting dash after every 4 character from here my question is what if the character interval is not constant like in this example it is only after every 4 what if the interval is 3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-" so it would appear like this 123-12-1234-123-123.
In this case, it is more convenient to just write normal code to solve the problem:
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
Sample usage:
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
$('.creditCardText').keyup(function() {
var foo = $(this).val().replace(/-/g, ""); // remove hyphens
// You may want to remove all non-digits here
// var foo = $(this).val().replace(/\D/g, "");
if (foo.length > 0) {
foo = format(foo, [3, 2, 4, 3, 3], "-");
}
$(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="creditCardText" />
While it is possible to do partial matching and capturing with regex, the replacement has to be done with a replacement function. In the replacment function, we need to determine how many capturing group actually captures some text. Since there is no clean solution with regex, I write a more general function as shown above.
You can split it using a regular expression. In this case, I'm using a expression to check for non-spaces with interval 3-2-4-3.
The RegExp.exec will return with a "match" array, with the first element containing the actual string. After removing the first element of the match, you can then join them up with dashes.
var mystring = "123121234123"
var myRegexp = /^([^\s]{3})([^\s]{2})([^\s]{4})([^\s]{3})$/g
var match = myRegexp.exec(mystring);
if (match)
{
match.shift();
mystring = match.join("-")
console.log(mystring)
}
Per further comments, the op clarified they need a fixed interval for when to insert dashes. In that case, there are several ways to implement it; I think regular expression would probably be the worst, in other words, overkill and overly complication solution.
Some simpler options would be to create a new character array, and in a loop append character by character, adding a dash too every time you get to the index you want. This would probably be the easiest to write and grok after the fact, but a little more verbose.
Or you could convert to a character array and use an 'insert into array at index'-type function like splice() (see Insert Item into Array at a Specific Index or Inserting string at position x of another string for some examples).
Pass the input value and the indexes to append the separator, first, it will remove the existing separators then just append separators on positions indexes.
export function addSeparators(
input: string,
positions: number[],
separator: string
): string {
const inputValue = input.replace(/-/g, '').split(''); // remove existing separators and split characters into array
for (let i = 0; i < inputValue.length; i++) {
if (positions.includes(i)) inputValue.splice(i, 0, separator);
}
return inputValue.join('');
}

Javascript change commas for points and points for commas?

I want to convert all commas in a string in points and vice-versa. However I don't know how to do it since I get all commas or points after the first change.
"1.000,20" should become "1,000.20"
How can this be done?
Try
"1.000,20".replace(/[\.,]/g, function (m) { return m == '.' ? ',' : '.' })
which uses the callback function option of replace()
Try this:
var str = "1,000.20";
//Split into components based on a period
var components = str.split('.');
//Iterate through each component, replacing commas with periods
var length = components.length;
for (var i = 0; i < length; i++) {
components[i] = components[i].replace(",", ".");
}
//Array.join can be slow but still useful - join with commas
str = components.join(",");

how to make string as array in java script?

I have a string value like:
1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i
I need to convert it into array in JavaScript like
1 2 3
4 5 6
7 8 9
etc.
Can any one please suggest me a way how to do this?
You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.
function chunkSplit(str) {
var chunks = str.split(';'), // split str on ';'
nChunks = chunks.length,
n = 0;
for (; n < nChunks; ++n) {
chunks[n] = chunks[n].split(','); // split each chunk with ','
}
return chunks;
}
var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");
If you need a multi-dimensional array you can try :
var array = yourString.split(';');
var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
array[i] = array[i].split(',');
}
Try the following:
var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
array.push(value.split(','));
});
jsFiddle Demo
Note: .forEach() not supported in IE <=8
The following split command should help:
yourArray = yourString.split(";");

Javascript array from string of numbers

I am trying to work with arrays in javascript. Consider the following code:
var visList = '1234,5678,9'
var visListArray = new Array(visList);
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
Why doesn't this split the array into individual numbers instead of all of them clumped together?
Any help would be really appreciated.
Many thanks
Create the array by calling split() on the string:
var visList = '1234,5678,9'
var visListArray = visList.split(",");
You cannot substitue a string that looks like code for actual code. While this would work:
var visListArray = new Array(1234,5678,9);
Yours doesn't because the string is not interpreted by the Array constructor as 3 comma separated arguments, it is interpreted as one string.
Edit: Note that calling split() on a string results in an Array of strings. If you want an Array of numbers, you'll need to iterate the Array converting each string to a number. One convenient way to do that is to use the map() method:
visListArray = visList.split(",").map(function (item) {
return +item;
});
See the compatibility note for using map() in older browsers.
because its an string, try this:
var visList = '1234,5678,9'
var visListArray = [].concat(visList.split(','));
for (i = 0; i <= visListArray.length - 1; i++) {
alert(visListArray[i]);
}
You have to use string.split
var visList = '1234,5678,9'
var visListArray = visList.split(",");
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
To convert a symbol-separated list into an array, you may use split(symbol):
var list = "1221,2323,4554,7667".split(",");
for (var i = 0, il = list.length; i < il; i++) {
alert( +list[i] ); // a casting from string to number
}

Categories

Resources