I have a Number in French: a='20 000 000'. I want to to add 1 to this number and put again it in French: a='20 000 001'`
I am using in JavaScript
a=Intl.NumberFormat('fr-FR').format(parseInt(document.getElementById('lblndescargas').innerText.replaceAll(' ',''))+1)
The first time it pass through it it gives 20 000 001. But the second time it gives 21. It seems like the space is not valid as separator.
Why? One year later I make the same question.
And replaceAll( / |\s/g, '' ) doesn't work. It is strange.
Now the number is
1 136
Internally it is
1 136
I do
alert(document.getElementById(gvdeglse').innerHTML.replaceAll(/\ \;|\s/g,''))
But it doesn't work, doesn't change. Can u try it and tell me, please? Maybe it is my browser.
Thanks in advance
Something like that?
var a = '20 000 000';
// Remove all spaces and parse Int
var b = parseInt(a.replace(/\s/g,''))+1;
var c = Intl.NumberFormat('fr-FR').format(b);
console.log(c); // 200 000 001
The straightforward approach would be to convert the French string number to an integer, increment it, and then convert back:
a = '20 000 000';
console.log(a); // 20 000 000
a = parseInt(a.replace(/\s+/g, ''), 10) + 1; // 20000000 => 20000001
a = a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' '); // 20 000 001
console.log(a);
But the best practice here would be to always maintain the amount internally in your JavaScript code as an integer. Only when you want to display it using French formatting, then use the latter part of my answer (or the formatting options given in the other answers).
You could use numeral.js library in this way:
numeral.register('locale', 'fr', {
delimiters: {
thousands: ' ',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème';
},
currency: {
symbol: '€'
}
});
numeral.locale('fr');
let myNumeral = numeral("20 000 000").add(1);
console.log(myNumeral.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
Related
I am trying to split a string which is of the following format -
text = "some random words 22 minutes go some text that follows". I am only concerned about "some random words".
The text can have 'minute' or 'hour' or 'hours' in it. I want to split and get the string that is before the digits. I cannot split based on digits only because the initial part can have digits too.
I tried to handle this with split and if conditions. But those are not fast enough. I am struggling to deal this with typescript regex group. Any suggestions would be very helpful
The function that I used was -
export function splitstring(msg: string): string
{
if (msg.includes('minute'))
{
return msg.toLowerCase().split('minute')[0];
}
if (msg.includes('minutes'))
{
return msg.toLowerCase().split('minutes')[0];
}
if (msg.includes('hour'))
{
return msg.toLowerCase().split('hour')[0];
}
if (msg.includes('hours'))
{
return msg.toLowerCase().split('hours')[0];
}
return msg;
}
Sounds like you can use .match(/(.*)\W\d+\W(minute|hour)/)[1]
var text = "some random words 22 minutes go some text that follows";
console.log(
text.match(/(.*)\W\d+\W(minute|hour)/)[1]
)
var text = "some random words 22 inute go some 12 hours text that follows";
console.log(
text.match(/(.*)\W\d+\W(minute|hour)/)[1]
)
var text = "some 18 random words 22 minutes go 11 some text that follows";
console.log(
text.match(/(.*)\W\d+\W(minute|hour)/)[1]
)
I am extracting text from a server. The data I'm extracting is not organized for further use. The text I'm extracting looks like this:-
>>[Extracted] id: 194805284, got 55 points from jones (252906152669) date: 15/04/19 08:44:40 you have 30 points remaining
I don't want all this text I only want the id, points, number, and date.
Note: I might extract more than one of the message once in a while.
So to extract the id, points, number, and date, I wrapped every word with a span tag and then used this code:
var getData = {
//gets the id, points, date and number respectively
number1 : $('span:contains("id:")').next().text(),
amount : $('span:contains("got")').next().text(),
time : $('span:contains("date:")').next().text(),
number : $('span:contains("date:")').prev().text()
}
The reason I'm using this code is that I might extract automatically more than 1 message, so with every message that gets extracted, every word that it contains is the same except the id, points, date, and number.
I used the above code to extract the data I want, but this time there was 2 [extracted] messages, look below.
HTML
<p>[Extracted] id: 194805284, got 55 points from jones (252906152669)
date: 15/04/19 08:44:40 you have 30 points remanining [Extracted] id: 193537533, got 3 points from Micheal (907794804)
date: 14/04/19 10:15:32, you have 100 points remaining</p>
<div class="processed-data">
</div>
CSS:
span {
border: 1px solid red;
}
JS:
// wrap every word with <span> tag
var words = $("p").text().split(" ");
$("p").empty();
$.each(words, function(i, v) {
$("p").append($("<span>").text(v));
});
//extract the id, points, time and number respectively
var getData = {
number1: $('span:contains("id:")').next().text(),
amount: $('span:contains("got")').next().text(),
//amount : $('span:contains("got")').next().text().substring(1),
time: $('span:contains("date:")').next().text(),
number: $('span:contains("date:")').prev().text()
}
// Output the extracted data to .processed-data div
$('.processed-data').append("thisTime = { [id: " + getData.number1 + " amount: " + getData.amount + ", time: " + getData.time + " number: " + getData.number + "]}'");
Here's a JSFiddle
output:
thisTime = {[id: 194805284,193537533, amount: 553, time: 15/04/1914/04/19 number: (252906152669) (907794804) ]}'
The results I expect are:
For each [extracted] message to get its own array. By using a loop or anything else.
Example:
Now I'm getting this;
thisTime = {
[id: 194805284,193537533, // All the ids are stored in 1 array data
amount: 553, // All the points are stored in 1 array data e.t.c
time: 15/04/1914/04/19
number: (252906152669) (907794804)]
}
I want to get:
thisTime = {
[id: 194805284,
amount: 55,
time: 15/04/19
number: (252906152669)],
[id:193537533,
amount: 3,
time: 14/04/19
number: (907794804)]
}
I only want each message I extract to have its own array.
I suggest you use Regex to solve it, I think is better than Jquery method that you are using.
See a possible Regex solution:
var text = '[Extracted] id: 194805284, got 55 points from jones (252906152669) date: 15/04/19 08:44:40 you have 30 points remanining [Extracted] id: 193537533, got 3 points from Micheal (907794804) date: 14/04/19 10:15:32, you have 100 points remaining';
var textArray = text.split('[Extracted]');
var regularExpression = /id:\s+([0-9]+).+got\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+date:\s+([0-9\/\s:]+)/i;
var output = [];
var item;
for(var i = 1; i < textArray.length; i++){
item = textArray[i].match(regularExpression);
output.push({
id: item[1].trim(),
amount: item[2].trim(),
time: item[4].trim(),
number: item[3].trim()
});
}
console.log(output);
You could easily use a regular expression (Regex) to solve this -- is there any particular reason you're wrapping each word in a span?
The following regular expression should match all tokens in your string:
id:\s+(\d+),\s+got\s+(\d+)\s+points\s+from\s+.+?\s+\((\d+)\)\s+date:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)
I'm using \s+ here instead of spaces because it seems the spacing in your above template is inconsistent, and just to be safe I like to use \s+ for any whitespace of any quantity.
You can extract a message like so...
const regex = /id:\s+(\d+),\s+got\s+(\d+)\s+points\s+from\s+.+?\s+\((\d+)\)\s+date:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/; // construct the regex literal
const message = // some string matching your "extracted" template
const match = message.match(regex); // now your match contains all the data
const [fullMatch, idString, pointString, dayString, monthString, yearString, hourString, minuteString, secondString] = match; // you don't have to destructure, but this is the order of the capturing groups.
You should also be able to match multiple as well, by doing the following...
let match;
while (match = regex.exec(message)) {
// now match can be handled the same way as above. You could alternatively push the matches to a list as well here.
}
Your issue is getData. I suggest to decompose the string splitting on Extracted and after on spaces. After, you can select sub spans grouping by sentences and filter in order to create an array containing one or more objects.
var sentences = $("p").text().split("\[Extracted\]").slice(1);
$("p").empty();
$.each(sentences, function(i, v) {
var words = ['Extracted'].concat(v.trim().split(/ +/));
$.each(words, function(idx, word) {
$("p").append($("<span/>", {text: word.trim()}));
});
});
var result = {thisTime: $("p span:contains(Extracted)").map(function(idx, txt) {
var x = $(this).nextUntil('span:contains(Extracted)');
return {id: x.filter('span:contains("id:")').next().text(),
amount: x.filter('span:contains("got")').next().text(),
time: x.filter('span:contains("date:")').next().text(),
number: x.filter('span:contains("date:")').prev().text()};
}).get()};
$('.processed-data').append(JSON.stringify(result));
span {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>[Extracted] id: 194805284, got 55 points from jones (252906152669)
date: 15/04/19 08:44:40 you have 30 points remanining [Extracted] id: 193537533, got 3 points from Micheal (907794804)
date: 14/04/19 10:15:32, you have 100 points remaining</p>
<div class="processed-data">
</div>
For example, I have user input any string: "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. These are just examples, the user can input any string.
I want to map this to integer cardinality:
"1st" -> 0
"2nd" -> 1
"third" -> 2
"fourth" -> 3
"fifth" -> 4
"9999th" -> 9998
So I need some kind of function where:
function mapCardinality(input: string): number{
let numberResult:number = ??
return numberREesult;
}
and I can call it like this:
console.log(
mapCardinality("1st"), // print 0
mapCardinality("2nd"), // print 1
mapCardinality("third"), // print 2
mapCardinality("fourth"), // print 3
mapCardinality("fifth"), // print 4
mapCardinality("9999th") // print 9998
);
Just look it up in an array or parse it as number:
const mapCardinality = c => {
const pos = ["1st", "2nd", "third", "fourth", "fifth"].indexOf(c);
return pos === -1 ? parseInt(c, 10) - 1 : pos;
};
I'd first ask what are the suffixes for all of the inputs?
'nd', 'rd', 'st', 'th' (most numbers)
If they enter an integer with the above prefixes then you could write the following function:
const getInteger = input => input.slice(0, -2);
const num = getInteger('999th');
console.log(num); // prints "999"
If they enter the elongated variant, it becomes much more complex, especially when it comes to typos, lack of spaces, etc. One way could be to map single digit words ('one', 'two', etc), tens ('ten', 'twenty', etc'), hundreds, thousands, and so on instead of every number imaginable. I would then parse and find matching words to give a result. That being said it is still limiting. I would strongly suggest limiting user input formats. Why can't the user input an integer?
const cardinalDictionary = {
'zero': 0,
'one': 1,
...,
'twenty',
...,
'hundred': 100,
'thousand': 1000,
};
I have many strings like this:
0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...
I would like these to become like this:
1, 2, ..., 10, 11, ..., 100, 101, ...
So I would like to remove all the 0 chars before a different char is present.
I tried with
.replace(/0/g, '')
But of course then it also removes the 0 chars after. Therefore for example 0010 becomes 1 instead of 10. Can you please help me?
You can do
.replace(/\d+/g, function(v){ return +v })
This is the shortes Solution
"0001".replace(/^0+/,""); // => 1
...
// Tested on Win7 Chrome 44+
^ ... starting of the String
0+ ... At least one 0
P.s.: test Regex on pages likes: https://regex101.com/ or https://www.debuggex.com
Update 1:
For one long String
"0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,"") // => 1, 2, 10, 11, 100, 101
// Tested on Win7 Chrome 44+
Examples:
// short Strings
var values = ['0001', '0002','0010', '0011','0100','0101'];
for(var idx in values){
document.write(values[idx] + " -> "+values[idx].replace(/^0+/,"") + "<br/>");
}
// one long String
document.write("0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,""));
Previously answered here.
.replace(/^0+(?!$)/, '')
Functionally the same as winner_joiner's answer, with the exception that this particular regex won't return a completely empty string should the input consist entirely of zeroes.
Use regex as /(^|,\s*)0+/g it will select 0's at beginning or followed by , and space
document.write('0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...'.replace(/(^|,\s*)0+/g,'$1'))
Explanation :
(^|,\s*)0+
Debuggex Demo
var text='00101';
var result=parseInt(text);
I have a pricelist that I would like to 'normalize', using the Javascript flavor of Regex.
Sample input:
1
1,99
1.99
10
100
5999 dollars
2 USD
$2,99
Our price 2.99
Price: $ 20
200 $
20,-
6 999 USD
Desired output:
1
1,99
1.99
10
100
5999
2
2,99
2.99
20
200
20
6999
I am getting rather good results with /([0-9.,\s]+)/ but I've got two problems:
The last sample line returns 6 instead of 6 999. I am not sure if it's possible to "remove" the space, preferably I would like to get 6999 but 6 999 is close enough.
Second last line returns 20, (which is logical since I include commas) but rather want 20 only in these cases.
Here is a fiddle: http://jsfiddle.net/8h8Tk/
If you really wanted to normalize your input, I would suggest you choose either , or . for your decimal value separator. However, if not, the jsfiddle above gives the correct output.
var output = input.replace(/[^0-9\.,\n]|,[^0-9]/g, "");
All it does is remove the characters you don't want.
Here's a version that is straight out of Match (or replace) a pattern except in situations s1, s2, s3 etc
The regex: (?:\d|[.,](?=\d))+|(\w+|.)
The left side of the alternation matches characters we want: digits, or dots and commas followed by digits. The right side matches and captures word characters or a single character, and we know these are not characters we want because they were not matched by the expression on the left.
When Group 1 is set, we replace with an empty string.
See the output in the online demo
<script>
var subject = "1 \n\
1,99 \n\
1.99 \n\
10 \n\
100 \n\
5 999 \n\
2 USD \n\
$2,99 \n\
Our price 2.99 \n\
Price: $ 20 \n\
200 $ \n\
20,- \n\
6 999 USD";
var regex = /(?:\d|[.,](?=\d))+|(\w+|.)/g;
replaced = subject.replace(regex, function(m, group1) {
if (group1 == "" ) return m;
else return "";
});
document.write("<pre>");
document.write(replaced);
document.write("</pre>");
</script>
The Output
1
1,99
1.99
10
100
5999
2
2,99
2.99
20
200
20
6999
If you don't mind doing it in two steps, first convert all commas to dots:
x = x.replace(/,/g, '.')
Then get rid of everything else:
x = x.replace(/[^.|0-9]+/g,'')
Replace what you don't want:
result = subject.replace(/[^\d.,]+/g, "");
How about /((?:[\d.,\s]+)?[\d]+)\b/g It extends from your original version