toString not getting applied to mixture of numbers, characters and special symbols - javascript

I am trying below code:-
var testrename = {
check: function() {
var str = 988,000 PTS;
var test = str.toString().split(/[, ]/);
console.log(test[0] + test[1]);
}
}
testrename.check();
I want output as- 988000
I was trying it on node

Your str variable's assigned value needs to be quoted in order to assign a string value to it, and for it to be recognized as a string.
It looks like what you're trying to do is extract the integer value of a string, so return 988000 from the string "988,000 PTS", and you would use parseInt(string) for that.
Update: The comma will break the parseInt function and return a truncated number, (988 not 988000) so you can use the replace function with a regular expression to remove all non-numeric values from the string first.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var testrename={
check :function() {
var str ="988,000 PTS";
cleanStr = str.replace(/\D/g,'');
var test = parseInt(cleanStr);
console.log(test);
}
} testrename.check();

Related

How to convert string to just the values of the string

I want to convert a string such as 'String' to the stripped version of that (I think thats the word?), something like this:
const strip = r => {
/* Code */
}
What I want is:
> strip('String')
> String
basically I just want it to remove the quotes from around a string
(I want the output to be a none-type)
Is this what you are after?
var test = "\"'String \" with 'quotes'\"";
test = test.replace(/['"]/g, "");
console.log("test: " + test);
In your example, the string passed as an argument to the strip function does not have quotes in its content. You're just telling that function that the r parameter is of type string with the content String.
To answer to your question, you can remove the quotes of a string by removing the first and last character:
const strip = str => {
return str.slice(1, -1);
}
strip('"String"') => String

Setting new value to str.charAt() [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 2 years ago.
I am trying to set the value of a character at a certain index in a string with a new character and I was wondering if it was possible with charAt() method. Something like this. str.charAt(1) will return string "e" at first.
let str = "hello";
str.charAt(1) = 'a';
str.charAt(1) will then return string "a".
My expected result is that the new string reads "hallo". But this results in an Uncaught ReferenceError: Invalid left-hand side in assignment. So is it simply not possible with this method?
charAt() is a function on String prototype,and you are trying to overriding it by that syntax; charAt() will return the character at the index and it is getter, not a setter; so you need to define your own custom method to achieve that, either by defining a pure function like snippet below or by defining it on String.prototype so you can use on any string;
let str = "hello";
function replaceStrAtIndex( str, index, letter ){
let modifiedStr = [...str];
modifiedStr[index] = letter;
return modifiedStr.join('')
}
console.log(replaceStrAtIndex(str, 1, 'a'))
or defining on string prototype:
String.prototype.replaceCharAt = function replaceStrAtIndex( index, letter ){
let modifiedStr = [...this];
modifiedStr[index] = letter;
return modifiedStr.join('')
}
let str = "hello";
console.log(str.replaceCharAt( 1, 'a'))

What does this obfuscated javascript snippet mean/do?

I cannot understand what this little snippet: var num = str.replace(/[^0-9]/g, ''); does.
Context:
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
var liczba = parseInt(num);
return liczba;
}
This JavaScript snippet will rip out anything that is not (the ^ part of the regular expression means "not") a number in str and then return an integer cast from the result as liczba. See my comments:
// This function will return a number from a string that may contain other characters.
// Example: "1.23" -> 123
// Example: "a123" -> 123
// Example: "hg47g*y#" -> 47
function retnum(str) {
// First let's replace everything in str that is not a number with "" (nothing)
var num = str.replace(/[^0-9]/g, '');
// Let's use JavaScript's built in parseInt() to parse an Integer from the remaining string (called "num")
var liczba = parseInt(num);
// Let's now return that Integer:
return liczba;
}
By the way, "liczba" means number in Polish :-)
This function takes a string, strips all non-number characters from it, turns the string into an integer, and returns the integer. The line you're asking about specifically is the part that strips out all non-number characters from the initial string, using the string.replace method.
It's not obfuscated, it's using a regular expression.
The expression matches all things which are not numbers then removes them. 0-9 means "any digit" and the ^ means "not". The g flag means to check the entire string instead of just the first match. Finally, the result is converted to a number.
Example:
var input = 'abc123def456';
var str = input.replace(/[^0-9]/g, '');
var num = parseInt(str);
document.querySelector('pre').innerText = num;
<pre></pre>
It literally just replaces anything which is not a number with a blank ('').

Checking the number inside a string in javascript

I have a string, say
var Str = 'My name is 123 and my name is 234'.
Now I split this as
var arrStr = Str.split(' ');
I iterate through the array and have different logic depending upon whether the word is a string or number. How do i check that? I tried typeof which didn't work for me.
EDIT:
After Seeing multiple answers. Now, I am in despair, which is the most efficient way?
If you care only about the numbers, then instead of using split you can use a regular expression like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\d+/g)
If you care about all pieces, then you can use another expression to find all non-space characters like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\S+/g)
Then iterate them one by one, and check if a given string is a number or not using the famous isNumeric() function posted by #CMS in this famous question.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Thanks to #Pointy and if you want them as numbers, input.match(/\d+/g).map(Number).
You need to attempt to convert your array values to an integer.
To iterate them you can use a for loop:
for(i=0;i<arrStr.length;i++) {
var result = !isNaN(+arrStr[i]) ? 'number' : 'string';
console.log(result);
}
Here I'm using a unary + to attempt to convert the value of each array value to a number. If this fails, the result will be NaN. I'm then using JavaScript's isNaN() method to test if this value is NaN. If it isn't, then it's a number, otherwise it's a string.
The result of this using the string you've provided is:
string
string
string
number
string
string
string
string
number
To use this in an if statement, we can simply:
for(i=0;i<arrStr.length;i++) {
if(isNaN(+arrStr[i])) {
/* Process as a string... */
}
else {
/* Process as a number... */
}
}
JSFiddle demo.
To expound on Sniffer's answer...
var input = "My name is 123 and my name is 234";
var numberArray = input.match(/\d+/g);
var wordArray = input.match(/[A-Za-z]+/g);
for (var number in numberArray)
{
//do something
}
for (var word in wordArray)
{
//do something
}
While researching, I found out about the Number() object. This is generally used to work with manipulation of numbers. MDN has a good documentation .
I found out that Number() returns NaN (Not a Number) when not passed a number. Since no number returns NaN, It could be a good way to check whether the passed object is string or a number literal.
So my code would be:
if (Number(arrStr[i]) == NaN){
//string
} else {
//number
}

Javascript extract numbers from a string

I want to extract numbers from a string in javascript like following :
if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.
Possible string values :
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
thinking of something like :
function beforeTo(string) {
return numeric_value_before_'to'_in_the_string;
}
function afterTo(string) {
eturn numeric_value_after_'to'_in_the_string;
}
i will be using these returned values for some calculations.
Here's an example function that will return an array representing the two numbers, or null if there wasn't a match:
function extractNumbers(str) {
var m = /(\d+)to(\d+)/.exec(str);
return m ? [+m[1], +m[2]] : null;
}
You can adapt that regular expression to suit your needs, say by making it case-insensitive: /(\d+)to(\d+)/i.exec(str).
You can use a regular expression to find it:
var str = "sure1to3";
var matches = str.match(/(\d+)to(\d+)/);
if (matches) {
// matches[1] = digits of first number
// matches[2] = digits of second number
}

Categories