How to convert non numeric string to int - javascript

For an assignment, i am trying to recreate a small project I once made in ASP.NET.
It converted each letter of a text to its int value, then added 1 en reconverted it to a char and put them all back into a single string.
Now I am trying to do this in Angular, but I am having trouble converting my non-numeric strings to its int value.
I tried it with ParseInt(), but this only seems to work if the string is a valid integer.
Is there any way to parse or convert non-numeric strings to an int value and how?

'String here'.split('').map(function (char) {
return String.fromCharCode(char.charCodeAt(0) + 1);
}).join('');
If you mean char code.

Thankx to the helpful insights of Claies and Damien Czapiewski I constructed the following solution.
Loop through each character in my string in a for loop.
Then, for each char I retrieved its value with charCodeAt()
And to return to a string value I used fromCharCode()
encode(msg:string):string {
let result: string = "";
if (msg) {
for (var i = 0; i < msg.length; i++) {
let msgToInt = msg.charCodeAt(i);
// do stuff here
result += String.fromCharCode(msgToInt);
}
}
return result;
}

Related

Javascript hexadecimal to ASCII with latin extended symbols

I am getting a hexadecimal value of my string that looks like this:
String has letters with diacritics: č,š,ř, ...
Hexadecimal value of this string is:
0053007400720069006E006700200068006100730020006C0065007400740065007200730020007700690074006800200064006900610063007200690074006900630073003A0020010D002C00200161002C00200159002C0020002E002E002E
The problem is that when i try to convert this value back to ascii it poorly converts the č,š,ř,.. and returns symbol of little box with question mark in it instead of these symbols.
My code for converting hex to ascii:
function convertHexadecimal(hexx){
let index = hexx.indexOf("~");
let strInfo = hexx.substring(0, index+1);
let strMessage = hexx.substring(index+1);
var hex = strMessage.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2){
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
console.log("Zpráva: " + str);
var strFinal = strInfo + str;
return strFinal;
}
Can somebody help me with this?
First an example solution:
let demoHex = `0053007400720069006E006700200068006100730020006C0065007400740065007200730020007700690074006800200064006900610063007200690074006900630073003A0020010D002C00200161002C00200159002C0020002E002E002E`;
function hexToString(hex) {
let str="";
for( var i = 0; i < hex.length; i +=4) {
str += String.fromCharCode( Number("0x" + hex.substr(i,4)));
}
return str;
}
console.log("Decoded string: %s", hexToString(demoHex) );
What it's doing:
It's treating the hex characters as a sequence of 4 hexadecimal digits that provide the UTF-16 character code of a character.
It gets each set of 4 digits in a loop using String.prototype.substr. Note MDN says .substr is deprecated but this is not mentioned in the ECMASript standard - rewrite it to use substring or something else as you wish.
Hex characters are prefixed with "0x" to make them a valid number representation in JavaScript and converted to a number object using Number. The number is then converted to a character string using the String.fromCharCode static method.
I guessed the format of the hex string by looking at it, which means a general purpose encoding routine to encode UTF16 characters (not code points) into hex could look like:
const hexEncodeUTF16 =
str=>str.split('')
.map( char => char.charCodeAt(0).toString(16).padStart(4,'0'))
.join('');
console.log( hexEncodeUTF16( "String has letters with diacritics: č, š, ř, ..."));
I hope these examples show what needs doing - there are any number of ways to implement it in code.

Reshape String, inserting "\n" at every N characters

Using JavaScript functions, I was trying to insert a breakline on a string at every N characters provided by the user.
Just like this: function("blabla", 3) would output "bla\nbla\n".
I searched a lot of answers and ended up with a regex to do that, the only problem is, I need the user's input on the matter, so I need to stuck a variable on this regex.
Here's the code:
function reshapeString(string, num) {
var regex = new RegExp("/(.{" + num + "})/g");
return string.replace(regex,"$1\n");
}
reshapeString("blablabla", 3);
This is currently not working. I tried to escape the '/' characters, but I'm screwing up at some point and I don't know where.
What am I missing? Is there any other way to solve the problem of reshaping this string?
You need a string for the regexp constructor, without /, and you can omit the group by using $& for the found string.
function reshapeString(string, num) {
var regex = new RegExp(".{" + num + "}", "g");
return string.replace(regex,"$&\n");
}
console.log(reshapeString("blablabla", 3));
How about a one-liner?
const reshapeString = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')
Explanation:
So first thing we do is split the string into a character array
Now we use a reduce() statement to go through each element and reduce to a single value (ie. the final string you're looking for!)
Now i%N should give a non-zero (ie. a truthy value) when the index is not a multiple of N, so we just add the current character to out accumulator variable o.
If i%N is in fact 0 (then it's falsey in value), and we append:
o (the string so far) +
\n (the appended character at the N'th interval)
c (the current character)
Note: We also have a !i check, that's for ignoring the first char since, that may be considered un-intended behavior
Benchmarking
Regex construction and replace also requires string re-construction and creating an FSA to follow. Which for strings smaller than 1000 should be slower
Test:
(_ => {
const reshapeString_AP = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')
function reshapeString_Nina(string, num) {
var regex = new RegExp(".{" + num + "}", "g");
return string.replace(regex,"$&\n");
}
const payload = 'a'.repeat(100)
console.time('AP');
reshapeString_AP(payload, 4)
console.timeEnd('AP');
console.time('Nina');
reshapeString_Nina(payload, 4)
console.timeEnd('Nina');
})()
Results (3 runs):
AP: 0.080078125ms
Nina: 0.13916015625ms
---
AP: 0.057861328125ms
Nina: 0.119140625ms
---
AP: 0.070068359375ms
Nina: 0.116943359375ms
public static String reshape(int n, String str){
StringBuilder sb = new StringBuilder();
char[] c = str.replaceAll(" " , "").toCharArray();
int count =0;
for (int i = 0; i < c.length; i++) {
if(count != n){
sb.append(c[i]);
count++;
}else {
count = 1;
sb.append("\n").append(c[i]);
}
}
return sb.toString();
}
Strings are immutable so whatever you do you have to create a new string. It's best to start creating it in the first place.
var newLineForEach = (n,s) => s && `${s.slice(0,n)}\n${newLineForEach(n,s.slice(n))}`,
result = newLineForEach(3,"blablabla");
console.log(result);
So my tests show that this is by far the fastest. 100K iterations resulted Nina's 1260msec, AP's 103msec and Redu's 33msec. The accepted answer is very inefficient.

Safest delimiter or convert from javascript hashmap to java linked map?

I have data like this, TITLE is the name of variable and below it is the string data (Please note the data can be different sometimes)
TITLE1
abcd
TITLE2
abcde
TITLE3
acd,sdssds!###$#$#%$%$^&**()aas
Now, I want to to send these three to java and want to make a linked map from them I did like this
JAVASCRIPT
var string = "TITLE1=abcd, TITLE2=abcde, TITLE3=acd,sdssds!###$#$#%$%$^&**()aas"
and used it in java as
JAVA
LinkedHashMap <String, String> selectedCheckBoxMap = new LinkedHashMap <String, String> ();
String[] pairs = selectedCheckBoxTokens.split (",");
for (int i = 0; i < pairs.length; i++)
{
String pair = pairs[i];
String[] keyValue = pair.split ("=");
selectedCheckBoxMap.put (keyValue[0], keyValue[1]);
}
But this breaks on "," as delimiter as TITLE3 already has character ','
I then used this character instead of "," as delimiter "‡", but this not a good approach.
What should I do ? Should I change it to hashmap in javascript ? But how to convert hashmap from javascript to JAVA directly ? Or should I use some other delimiter ?
The delimiter should be character that we cannot type or ever come across in text.
Thanks,
Aiden
if your data is that regular you could split on a ", " instead.
if spaces are in your value sets, then you need to mark your data values... be that with single/double quotes or some other unique marker.
building a JSON object and then delivering it would likely be a more robust solution.
If you use JSON:
var s = {};
s["TITLE1"] = "skladjdklsajdsla";
s["TITLE2"] = "*&^&^%&*,,()*&";
s["TITLE3"] = "acd,sdssds!###$#$#%$%$^&**()aas";
That code will create an Java Script Object:
Object {
TITLE1="skladjdklsajdsla",
TITLE2="*&^&^%&*,,()*&",
TITLE3="acd,sdssds!###$#$#%$%$^&**()aas"
}
You can parse the Object using a JSON library for Java:
http://www.oracle.com/technetwork/articles/java/json-1973242.html
See: How to parse JSON in Java
JSON Standard: http://www.json.org/
When generating the string to be send, escape the commas and the equal signs in the values by replacing them with something else like %2C and %3D
Then or server side unescape by doing
selectedCheckBoxMap.put (keyValue[0], keyValue[1].replace("%2C",",").replace("%3D","="));
Using common characters as a delimiter is error-prawn ever since. You have to escape each delimiter you use and then parse the string by yourself. This means, that you have to call value.replace(/([\\=,])/g, '\\$1') on each entry, before appending it to your datastring.
Even if i would recommend you using JSON, as Alzoid proposed, here is an untested implementation you could use to decode the input (assuming '\' is your escape character):
boolean escaped = false;
boolean waitingForKey = true;
String key = "";
String current = "";
for (int i = 0; i < data.length(); i++) {
char character = data.charAt(i);
if (escaped) {
current += character;
escaped = false;
continue;
}
if (waitingForKey && Character.isWhitespace(character)) {
continue;
} else if (waitingForKey) {
waitingForKey = false;
}
switch (character) {
case '\\':
escaped = true;
break;
case '=':
key = current;
current = "";
break;
case ',':
map.put(key, current);
current = "";
key = "";
waitingForKey = true;
break;
default:
current += character;
}
}
if (!data.isEmpty()) {
map.put(key, current);
}

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.
For example: "In 2015, I want to know how much does iPhone 6+ cost?"
Output: 2021
Here is my current code:
var str = "In 2015, I want to know how much does iPhone 6+ cost?";
function sumFromString(str){
var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var StringList = finalString.split(" ");
var sum = [];
for (i = 0; i < StringList.length; i++)
if (isInt(StringList[i])
sum.add(StringList[i]);
sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);
My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.
I can't get the next part to work.
What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.
Much simpler:
function sumFromString(str) {
return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}
Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.
For the sake of variety, here's a way to do it without regular expressions:
var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
if (!isNaN(parseInt(myArray[i]))) {
total += parseInt(myArray[i]);
}
}
Fiddle Demo
note: If there's a chance myString could be null, you'd want to add a check before the split.
Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.
Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.
string.split(' ').filter(function(word) {
return /\d+/.test(word) }
}).map(function(s) {
return s.replace(/\D/, '')
}).reduce(function(a,b) {
return Number(a) + Number(b);
});

how to check whether a var is string or number using javascript

I have a variable var number="1234", though the number is a numeric value but it is between "" so when I check it using typeof or by NaN I got it as a string .
function test()
{
var number="1234"
if(typeof(number)=="string")
{
alert("string");
}
if(typeof(number)=="number")
{
alert("number");
}
}
I got always alert("string"), can you please tell me how can I check if this is a number?
As far I understand your question you are asking for a test to
detect if a string represents a numeric value.
A quick test should be
function test() {
var number="1234"
return (number==Number(number))?"number":"string"
}
As Number, if called without the new keyword convert the string into a number.
If the variable content is untouched (== will cast back the numeric value to a string)
you are dealing with a number. It is a string otherwise.
function isNumeric(value) {
return (value==Number(value))?"number":"string"
}
/* tests evaluating true */
console.log(isNumeric("1234")); //integer
console.log(isNumeric("1.234")); // float
console.log(isNumeric("12.34e+1")); // scientific notation
console.log(isNumeric(12)); // Integer
console.log(isNumeric(12.7)); // Float
console.log(isNumeric("0x12")); // hex number
/* tests evaluating false */
console.log(isNumeric("1234e"));
console.log(isNumeric("1,234"));
console.log(isNumeric("12.34b+1"));
console.log(isNumeric("x"));
The line
var number = "1234";
creates a new String object with the value "1234". By putting the value in quotes, you are saying that it a string.
If you want to check if a string only contains numeric digits, you can use regular expressions.
if (number.match(/^-?\d+$/)) {
alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
alert("It's a decimal number!");
}
The pattern /^\d+$/ means: at the start (^) of the string, there is an optional minus sign (-?), then a digit (\d), followed by any more digits (+), and then the end of the string ($). The other pattern just looks for a point between the groups of digits.
See parseInt and parseFloat
Convert it to a number then compare it to the original string.
if ( parseFloat(the_string,10) == the_string ) {
// It is a string containing a number (and only a number)
}
because var number="1234" is a string. the double quotes makes it a literal.
if you want a number use it like this
var number = 1234;
Update:
If you are taking the input from a input tag forexample, the dataType will be string, if you want to convert it to a number, you can use the parseInt() function
var number = "1234";
var newNumber = parseInt(number);
alert(typeof newNumber); // will result in string
Another easy way:
var num_value = +value;
if(value !== '' && !isNaN(num_value)) {
// the string contains (is) a number
}

Categories

Resources