I have a string in JavaScript and at some places corresponding to a regex (lower case followed by upper case), I would like to insert between upper and lower case the backspace character.
This is an example:
Manufacturer: SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels
It should become:
Manufacturer: Samsung
Warranty: 12 months
Unlocking: Any operator
Iris scanner: No
Screen size: 5.7 inches
Display resolution: 2560 x 1440 pixels
You can match on /([a-z])([A-Z])/g and replace with "$1\n\n$2", then prepend "Manufacturer: " to the beginning of the string.
const s = "SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels";
const res = "Manufacturer: " + s.replace(/([a-z])([A-Z])/g, "$1\n\n$2");
console.log(res);
Related
This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 9 months ago.
I am making a calculator where user can past numbers with spaces like
20 30 40 60 50
and it will calculate all in total = 200
How I can convert this string "20 30 40 60 50" to Numbers with spaces? Because I'll than replace the space with +
You can use split with map for transform string to number then use reduce for sum array like:
const string = '20 30 40 60 50';
const arrayNumbers = string.split(' ').map(el => parseInt(el));
const sum = arrayNumbers.reduce((sumCounter, a) => sumCounter + a, 0);
console.log(arrayNumbers, sum);
Please note: If you plan to use decimals use parseFloat instead of parseInt
Reference:
String.prototype.split()
Array.prototype.map()
Array.prototype.reduce()
On javascript (not using node), I am facing different results when CBOR encoding using library (https://github.com/paroga/cbor-js) and when using CBOR online (https://cbor.me/). Note that even using a more recent CBOR library, result is identical.
For instance setting an object such as :
const initial = { 1: "John", "-2": 456 };
Encoding using CBOR online gives : a201644a6f686e622d321901c8. Details are :
A2 # map(2)
01 # unsigned(1)
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
Now encoding using CBOR library on javascript gives a different result : a26131644a6f686e622d321901c8
When decoding this above Hexadecimal on CBOR online, I got : {"1": "John", "-2": 456}. Result is almost identical than the constant 'initial' except that key 1 now appears with a quote (").
CBOR online re-formats my hexadecimal value to a more 'readable' view :
A2 # map(2)
61 # text(1)
31 # "1"
64 # text(4)
4A6F686E # "John"
62 # text(2)
2D32 # "-2"
19 01C8 # unsigned(456)
See below my Javascript code :
//convert an array of bytes (as 8 bits) to string of Hex. ensure that Hex value are not return with 1 digit but 2 digits. ie '01' instead of '1'
function toHexString(byteArray) {
var s = '';
byteArray.forEach(function(byte) {
s += ('0' + (byte & 0xFF).toString(16)).slice(-2);
});
return s;
}
const initial = { 1: "John", "-2": 456 };
var encoded = CBOR.encode(initial);
var encodedHex = toHexString(Array.from(new Uint8Array(encoded)));
console.log ( encodedHex );
I could manually replace specific hexadecimal values such as :
'61 31 64' replaced by '01 64'
But not fancy doing it as list could be important to cover all possible options.
Does someone have a workaround as I need my result to be 'a201644a6f686e622d321901c8' and not 'a26131644a6f686e622d321901c8' ?
Object keys in Javascript
The CBOR specification, section 5.6 says:
In applications that need to interwork with JSON-based applications, conversion is simplified by limiting keys to text strings only
And indeed, the cbor-js package uses the Object.keys method here, which returns all keys as strings. Javascript does not distinguish between numbers and their string values and treats {'1':1, 1:2} as {'1':2} (whereas cbor.me treats this as a map with two entries).
Solution with a modified cbor-js
Your example suggests that you want non-negative numeric keys treated as numeric by CBOR. This can be achieved with the following patch on the cbor-js source code:
diff --git a/cbor.js b/cbor.js
--- a/cbor.js
+++ b/cbor.js
## -164,7 +164,10 ## function encode(value) {
writeTypeAndLength(5, length);
for (i = 0; i < length; ++i) {
var key = keys[i];
- encodeItem(key);
+ if (isNaN(key) || Number(key) < 0)
+ encodeItem(key);
+ else
+ encodeItem(Number(key));
encodeItem(value[key]);
}
}
With this change, Node.js gives me
> Buffer.from(cbor.encode({1:'John','-2':456})).toString('hex'))
'a201644a6f686e622d321901c8'
Or you could even treat negative numeric keys as numeric by leaving out the || Number(key) < 0 in the patch above. This gives
> Buffer.from(cbor.encode({1:'John','-2':456})).toString('hex'))
'a201644a6f686e211901c8'
A2 # map(2)
01 # unsigned(1)
64 # text(4)
4A6F686E # "John"
21 # negative(1)
19 01C8 # unsigned(456)
Solution with cbor
Unlike cbor-js, the cbor package allows you to encode a Javascript Map, which distinguishes numeric from string keys:
> Buffer.from(cbor.encode(new Map().set(1,'John').set(-2,456))).toString('hex')
'a201644a6f686e211901c8'
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>
I'm trying to random 8 digits number 0-7 , but without the 8 and 9
this is what I've done, but I can't exclude the 8 and 9
var b = Math.floor(Math.random()*90000000) + 10000000;
console.log(b)
is there any quick for random the exact 8 digits exclude number? or do I really have to random one by one and += until 8 digits ?
Convert to octal (which contains only the digits 0-7) and trim to the desired length:
b.toString(8).substr(0, 8)
You could get first the max number of the octal system with 8 places and use the decimal system for generating the random value and convert it back to the wanted system.
var max = parseInt(100000000, 8);
console.log(('0000000' + Math.floor(Math.random() * max).toString(8)).slice(-8));
You need a number of 8 digits in base 8.
This means you're looking for a (decimal) number between 8^7 and 8^8-1, converted to base 8.
This should do the trick :
// initialize min and max values
var vmin = Math.pow(8,7);
var vmax = Math.pow(8,8)-1;
// compute random number within range
var dec = Math.floor(Math.random()*(vmax-vmin))+vmin;
// convert to base 8
console.log(dec.toString(8));
Perhaps you would want something more like this:
var b = Math.floor(Math.random()*8);
console.log(b);
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