This question already has answers here:
jQuery / Get numbers from a string
(8 answers)
Closed 5 years ago.
I have strings like
'156p1m2s10c'
'15p13m22s3c'
'1644p31m142s3c'
out of which I want to get all numerics separately.
An array will also work like:
156
--
1
--
2
--
33
How to do it using Jquery. I tried code mentioned below, but it's all going wrong.
function myFunction() {
var str = "156p1m2s33c";
var prodId = cust_code.substring(0, url.indexOf('p'));
var metalId = cust_code.substring(url.indexOf('p') + 1, url.indexOf('m'));
var prodId = cust_code.substring(url.indexOf('m') + 1, url.indexOf('s'));
}
What is wrong in the code?
You can use String#match with a RegExp. You can use Array#map afterwards to convert the strings to numbers if needed.
var str = '156p1m2s33c';
var numbers = str.match(/\d+/g);
console.log(numbers);
What's wrong in your code:
cust_code and url are not part of the function. Refer to str.
You declare prodId twice.
You don't handle the number between "s" and "c".
You are doing a lot of duplicated search (index of p, index of m, etc...).
Your function doesn't return anything, or do anything with the results.
Using regular expressions is more fitting for this case.
function myFunction() {
var str = "156p1m2s33c";
var pI = str.indexOf('p');
var mI = str.indexOf('m');
var sI = str.indexOf('s');
var cI = str.indexOf('c');
var prodId = str.substring(0, pI);
var metalId = str.substring(pI + 1, mI);
var anotherId1 = str.substring(mI + 1, sI);
var anotherId2 = str.substring(sI + 1, cI);
return [prodId, metalId, anotherId1, anotherId2];
}
console.log(myFunction());
Related
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);
This question already has answers here:
Convert JavaScript String to be all lowercase
(15 answers)
Closed 3 years ago.
I have the following code:
var str = "abcabcABCABC"
var chars = str.split("");
var lettersCount = {};
for (var i = 0; i < chars.length;i++)
{
if (lettersCount[chars[i]] == undefined )
lettersCount[chars[i]] = 0;
lettersCount[chars[i]] ++;
}
for (var i in lettersCount)
{
console.log(i + ' = ' + lettersCount[i]);
}
This code is counting how many same letters are in a word. What am I trying is to convert the uppercase letters to lowercase so it should show like this: a - 4, b -4, now it shows: a - 2, A - 2.
I've just started with Js so please be good with me. :)
If you just need the string to be converted into lowercase letter then you can do it like this:-
var str = "abcabcABCABC";
var newStr = str.toLowerCase();
console.log(newStr);
Hope this helps.
I'm new to javascript so apologies if I've missed something simple. I'm working on a script to take a string from one cell in Sheets, add VAT at 5% to any applicable numbers and output the amended string in a new cell. I'm happy with the regex capturing the numbers I need, but getting the amended string correct is proving tricky.
So far the script looks like this:
function strReplace() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var str = sheet.getRange(4,2).getValue(); // A cell with a string like this: "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87"
var regex = /\d{1,8}(?:\.\d{1,8})/g // Regex to ignore numbers greater than 8 digits, including decimals
var newStr = str.match(regex);
for (var x = 0; x < newStr.length; x++) {
var newRates = newStr[x]*1.05;
var output = str.replace(newStr, newRates)
sheet.getRange(4,3).setValue(output);
}
}
I've tried a bunch of variations but with no success. I feel there is an easier way to achieve what I'm looking for from what I already have. Any recommendations would be much appreciated.
Thanks!
To do this kind of thing, you use the function callback version of replace:
var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g; // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
return 1.05 * match;
});
console.log(output);
You might choose to use parseFloat(match) rather than just using match, which relies on * coercing the string to number.
And you might consider .toFixed(2) on the result to round and format to two places (depending on whether you want to round the way it rounds). For instance:
var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g; // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
return (1.05 * match).toFixed(2);
});
console.log(output);
basically your solution is very close, you just needed tot assign the str.replace, use the newStr[x] and also wait to end the for to assign it into the cell.
check the sample below.
function strReplace() {
let str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g
var newStr = str.match(regex);
for (var x = 0; x < newStr.length; x++) {
var newRates = parseFloat(newStr[x]) * 1.05;
str = str.replace(newStr[x], newRates)
}
return str;
}
var replaced = strReplace();
console.log(replaced)
I've used var.split("_"); here. Example of a value I'm trying to get would be: 2_25000
However, below code results a NaN value.
function calculateTotal() {
var room_type_id = document.getElementById('room_type_id').value;
var room_type_cost = room_type_id.split("_");
var meal_type_id = document.getElementById('meal_type_id').value;
var meal_type_cost = meal_type_id.split("_");
var bed_type_id = document.getElementById('bed_type_id').value;
var bed_type_cost = bed_type_id.split("_");
var ext_beds_id = document.getElementById('ext_beds_id').value;
var reservation_duration = document.getElementById('reservation_duration').value;
document.getElementById('total_amount').value = ( Number(room_type_cost[1]) + Number(meal_type_cost[1]) + Number(bed_type_cost[1]) + Number(ext_beds_id) ) * Number(reservation_duration);
}
you may use number() function or parseInt() function but remember to also pass the base 10 second parameter in parseInt("23", 10), also you can prefix + symbol to convert it to integer.
for i.e., +"23" + 2
Try this one............
change
Number()
to
parseInt()
My javascript hash on my web page looks like:
{"7":{"prop1":234, ....}"101":{"prop1":121,....}
I'm trying to reference it like this:
var a = 7;
my_hash[a].prop1
But it doesn't seem to find the hash object at the key 'a', since a is an integer and my keys are strings.
How can convert it to a string?
I tried:
my_hash[" + a + "].prop1
But that didn't work either.
Just create a string:
var a = "7";
If you have a number already, and want to make it a string, coerce it to a string this way:
var n = 7;
var a = n + "";
So, these all will work:
my_hash["7"].prop1;
var a = "7";
my_hash[a].prop1;
var n = 7;
var a = n + "";
my_hash[a].prop1;
Edit: Some examples converting it to a string inline:
my_hash[7 + ""].prop1;
var n = 7;
my_hash[n + ""].prop1;
Why not this:
var a = "7";
my_hash[a].prop1
or
my_hash["7"].prop1
Also, I'm assuming this was just a copy/paste into SO issue, but there's a missing comma in this:
{"7":{"prop1":234, ....}"101":{"prop1":121,....}
should be:
{"7":{"prop1":234, ....}, "101":{"prop1":121,....}
var x = {"7":{"prop1":234},"101":{"prop1":121}};
var a = 7;
console.log(x[a+""].prop1);
http://jsfiddle.net/userdude/ZGWHU/
You can coerce the number into a string like gilly3 suggests. But you can also just call .toString on the number itself. For example:
(1).toString() === "1" // evaluates to true.
This also works for variables so you could do this:
for (var i=0; i<10; i++) {
property = myObject[i.toString()]["property"];
// do something with property
}