I'm making a prep course for a bootcamp - yes, n00b over here! - and I'm stuck in this particular exercise about String Methods
I need to manipulate this original string 'supercalifragilisticexpialidocious' and obtain the following version: docious-ali-expi-istic-fragil-cali-rupus
I've tried this:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(9,5);
var newWord7 = bigWord.slice(5,9);
var newWord8 = bigWord.charAt(4);
var newWord9 = bigWord.slice(1,2);
var newWord10 = bigWord.charAt(2);
var newWord11 = bigWord.slice(32);
console.log(newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7,newWord8,newWord9,newWord10,newWord11);
Does anybody have a hint for me? Can someone help me out?
Cheers!
Here is a code snipet that works. It does not answer your question though:
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
console.log([newWord1,newWord2,newWord3,newWord4,newWord5,newWord6,newWord7].join("-"));
The problems are:
you used .slice(9,5) for word 6 which is incorrect, because 9 is behind the 5 and therefore newWord6 did not get the correct result, but "" (empty string)
you did not add up word 7 to a whole, but printed its elements separately
you have to print minus characters in between
either by putting + "-" + between every variables
or by adding up an array like mine and use the join() operator
I would go for some Regexep stuff
const original = 'supercalifragilisticexpialidocious';
const expected = 'docious-ali-expi-istic-fragil-cali-repus';
// the most common way to reverse a string is to explode it to an array and use the standard reverse method and then joining it back again as a string
function reverseString(str) {
return str.split("").reverse().join("");
}
// the replacer method do the job of concataining words joining them by dash and call the reverse method for the last matched word.
function replacer(match, p1, p2, p3, p4, p5, p6, p7, offset, string) {
return [p7, p6, p5, p4, p3, p2, reverseString(p1)].join('-');
}
// pick the words by block of letters
const actual = original.replace(/(\w{5})(\w{4})(\w{6})(\w{5})(\w{4})(\w{3})(\w{7})/, replacer);
console.log(expected === actual);
I tried to make a simple example for you while keeping things somewhat dynamic so you can learn.
Assuming you want the words sliced from the end of the string to the start of it and then combined back together in reverse with a - then all you need to 'hardcode' is the length of each word to slice (from the start to the end) and then loop through that and slice out your words. So if you want to turn supercalifragilisticexpialidocious into docious-ali-expi-istic-fragil-cali-super you can do this:
var bigWord = 'supercalifragilisticexpialidocious';
var slices = [5, 4, 6, 5, 4, 3, 7];
var words = [], lastSlice = 0;
slices.forEach(slice => {
words.push(bigWord.slice(lastSlice, lastSlice + slice))
lastSlice += slice;
});
// Reverse the sliced words and join them back together with -
words = words.reverse().join('-');
console.log(words); // outputs docious-ali-expi-istic-fragil-cali-super
var bigWord = 'supercalifragilisticexpialidocious';
var newWord1 = bigWord.slice(27);
var newWord2 = bigWord.slice(24,27);
var newWord3 = bigWord.slice(20,24);
var newWord4 = bigWord.slice(15,20);
var newWord5 = bigWord.slice(9,15);
var newWord6 = bigWord.slice(5,9);
var newWord7 = bigWord.charAt(4) + bigWord.slice(1,2) + bigWord.charAt(2) + bigWord.slice(32);
var newBigWord =(newWord1+'-'+newWord2+'-'+newWord3+'-'+newWord4+'-'+newWord5+'-'+newWord6+'-'+newWord7);
console.log(newBigWord);
Related
I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);
I've created an associative array for index spaces inside a sentence for example:
sentence: hello how are you? (spaces between the word 'hello' to 'how')
so my array looks like this:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
but when I use 'for' loop its show me (using alert) the indexes 0,1,2,3 first and after them the sub-indexes, its mixed up my array order, any idea?
here my code:
function words_indexer(user_content)
{
var words_array = user_content.split(" ");
var indexed_words = {};
var word_counter = 0
var last_word_counter = 0
$.each(user_content, function(word_key,word_value){
if(word_value === ''){
var indexed_key = last_word_counter + '_' + word_key;
indexed_words[indexed_key] = word_value;
}else{
var indexed_key = word_counter;
indexed_words[indexed_key] = word_value;
last_word_counter = word_counter;
word_counter++;
}
});
for (var key in indexed_words) {
alert(key + ' ' + indexed_words[key]);
}
}
If your array index needs an extra level of structure then it may be better to just create a nested array instead:
indexed_words[0] = hello
indexed_words[0][1] = space
indexed_words[0][2] = space
indexed_words[0][3] = space
indexed_words[0][4] = space
indexed_words[0][5] = space
indexed_words[0][6] = space
indexed_words[0][7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
I believe adding an underscore to your array key may actually cause Javascript to consider it as being a string which would bump your numeric keys up above it.
You can't use non-numeric indexes for arrays in javascript (a_b is not considered numeric). For this you probably should use an object. And then loop through it like this:
for(var word_key in indexed_words) {
if(!indexed_words.hasOwnProperty(word_key)) continue;
var word_value = indexed_words[word_key];
// Your code
}
I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);
I have just one question maybe stupid (like every day)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){ยด
tab.push(word[i])
}
}
console.log(tab.join(', ');
but it is dont work, i dont know how to use variable with regexpr, thanks, sorry for my english
var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null
Here is the code, but is used the test() instead of match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);
The solution using RegExp.test and Array.filter functions:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
Also, there's an additional approach using Array.indexOf function without any regex which will give the same result:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});
Is there by any chance a built-in javascript function that parses:
var string = '[2,1,-4]';
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
to
var array = [2,1,-4];
var multiArray = [[-3,2,-1],[2,-3,2],[1,-1,3]];
or do I have to write a custom function for this?
Assuming your correct your multiString to the correct format
(ie. '[[-3,2,-1],[2,-3,2],[1,-1,3]]')
Then yes.
array = JSON.parse(string);
multiArray = JSON.parse(multiString);
For completeness, you can use eval:
var s = '[1,2,3]';
var a = eval(s);
however if the string is valid JSON, then as Niet suggested, JSON.parse is a much better solution.
If you want to do this on your own, it can be done using substring and split. A possible solution could look like this:
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
var string = '[2,1,-4]';
function parse(input) {
var s = input;
// remove leading [ and trailing ] if present
if (input[0] == "[") {
s = input.substring(0, input.length);
}
if (input[input.length] == "]") {
s = s.substring(input.length-1, 1);
}
// create an arrray, splitting on every ,
var items = s.split(",");
return items;
}
// items is now an array holding 2,-1,4
var items = parse(string);
You can then split the bigger string into smaller chunks and apply the function to each part using array.map:
function parseAOfA(input) {
var s = input.substring(0, input.length).substring(input.length-1, 1);
s = s.substring(0, s.length).substring(s.length-1, 1);
s = s.split("][");
var items = s.map(parse);
return items;
}
var items = parseAOfA(multiString);