How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')
Related
Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);
When you first learn to code, you learn there are different value types. Strings, like "Hello", booleans, like true, and numbers, like 1. How can I set the value of a <p> tag to be a number and not a string? Or is there a separate number tag?
Javascript is an untyped language. The variable type is deduced from the value of that variable. The type of a variable could also change a value of another type is assigned to it. So things like this (for example C language):
int a; // a is an int (it will be always an int)
float f = 5.34; // f is a float (it will always be a float)
do not exist in Javascript. Javascript could use the same variable to store multiple types without redeclaring the variable.
var a = 45; // a type is deduced from the current assignement so for now it's a number
a = "string"; // now the type of a is a string not a number anymore
You can explicitly or implicitly convert one type to another when needed.
Explicit Conversation:
you can convert a number into a string (although it will not be necessary) using .toString like this:
var num = 456;
console.log("num is of type: " + typeof(num));
var str = num.toString(); //explicitly change num to string
console.log("str is of type: " + typeof(str));
You can also convert a string into a number explicitly (this is used a lot) using parseInt if the string is an integer, parseFloat if the string is a float, or Number to get any like this:
var str = '123.45.99';
console.log("str is of type: " + typeof(str));
var num1 = parseInt(str); // will parse an integer untill the first non integer character is found (will return 12 if str == "12ppp")
console.log("num1 is of type: " + typeof(num1));
var num2 = parseFloat(str); // parses a float untill the first non float character is found (will return 75.56 if str == "75.56.55abc"
console.log("num2 is of type: " + typeof(num2));
var num3 = Number(str); // get number representation of the string (will fail (return NaN) if the string is not a valid number like "123r33")
console.log("num3 is of type: " + typeof(num3));
Implicit Conversation:
Implicit conversation is when you let for the interpretter no other choice except of handling your variable as of your type. Thus preventing it from interpretting them incorrectly. You can acheive this using a lot of ways.
To implicitly convert a number into a string, just add an empty string to that number like this:
var num = 345;
console.log("num is of type: " + typeof(num));
var str = "" + num;
console.log("str is of type: " + typeof(str));
To convert a string into a number, there are multiple ways like this:
var str = '123.45';
console.log("str is of type: " + typeof(str));
var num1 = +str; // a unary operator (that is valid for numbers only) forces the interpretter to use the value of str as a number
console.log("num1 is of type: " + typeof(num1));
Since the + operator (not the unray one) could be used for both concatenation and the addition the interpretter will always favor the concatenation on the addition if one of the operands is a string. But the other operator (/, *, / and %) are only used for number, so when a string is divided by another number, the interpretter will be forced to use the value of the string as a number:
var str = "10";
var num1 = str + 5;
console.log("num1 is: " + num1 + " and it's of type: " + typeof(num1)); // print out the wrong expectation, because since one of the operands of the + is a string (str) the interpretter will think it's a concatenation
var num2 = str * 5; // since * could be used with just numbers, the interpretter is forced to use str as a number (implicitly converting str to a number)
console.log("num2 is: " + num2 + " and it's of type: " + typeof(num2));
// to make the + operator work you'll have to use the unary operator to implicitly convert str before adding the numbers
var num3 = +str + 5;
console.log("num3 is: " + num3 + " and it's of type: " + typeof(num3));
// ++ and -- are also used with just number ..
str++; // since str++ is str = something and that something is calculated as number str will implicitly take the value of a number thus when used again it will be deduced as a number
console.log("str is: " + str + " and it's of type: " + typeof(str)); // in the previous assignment, str took the value of a number thus becoming a number
HTML <p> tag specifically stands for paragraphs. So it is supposed to treat everything inside it as strings of text.
If you are sure it contains numerical value, you can convert it to a number using parseFloat(yourPtext.replace(',','')); and use it in your javascript code.
Assuming that you are using the <p> parameter as a paragraph of text..
Try wrapping the <p></p> in side a <div>
Then give it an id.
Like this:
<div id="myClass"><p></p></div>
Then add some javascript like so:
<script>
var element = document.getElementById("myClass");
element.innerText = "1";
</script>
Might want to to look at this link
http://www.w3schools.com/js/js_htmldom_html.asp
The <p> is the element used to wrap paragraphs. The value of a <p> tag is always text. Checking W3C HTML5 standard, you discover that the content model for <p> element is Phrasing content:
Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs.
So, you can display numbers inside a <p> element but they are always represented as strings. You can get the value of a paragraph as a string and then parse it to a number:
var par = document.getElementById('p1');
var val = par.innerHTML;
console.log('val:', typeof val); // Return "string"
var valNumber = parseInt(val); // Parsing the string value to integer
console.log('valNumber:', typeof valNumber); // Return "number"
<p id="p1">123</p>
Using jquery you can do so in 2 ways
1) var pText = $("p").text()
var number = Number(pText)
2) var pText = $("p").text()
var number = parseInt(pText,10)
or replace <p> tag with <input type="number" value="" >
var sssee = "581.30";
var ssser = "1,178.70";
var ssee = sssee.trim().replace(/,/g, "");
var sser = ssser.trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + parseFloat(ssee + sser))
In log i see:
ee 581.30
er 1178.70
total 581.301178
Why is it when adding replace to remove the , messes the computation.
Variables ssee and sser are both strings. When you peform ssee + sser it would return string 581.301178.70 which would be passed to parseFloat function then. When there are two decimal points, only first is taken as correct, that's why parseFloat returns 581.301178.
Check the snippet with correct solution.
var sssee = 581.30;
var ssser = "1178.70";
var ssee = String(sssee).trim().replace(/,/g, "");
var sser = String(ssser).trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + (parseFloat(ssee) + parseFloat(sser)))
You should also wrap ssee and ssser in String object before using trim and replace methods. Without doing that if you provide those variables as floats, instead of strings, your code won't work.
Your problem:
You concatenate two strings ("581.30" + "1,178.70") to one string ("581.301178.70"). Then you parse it to a float (581.301178).
Solution:
You need to parse each one to a float at first. After do your addition (parseFloat(ssee) + parseFloat(sser)).
I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.
I have a string like
:21::22::24::99:
And I want to find say if :22: is in said string. But is there a means of searching a string like above for one like I want to match it to with javascript, and if there is, does it involve regex magic or is there something else? Either way not sure how to do it, more so if regex is involved.
You can build the regular expression you need:
function findNumberInString(num, s) {
var re = new RegExp(':' + num + ':');
return re.test(s);
}
var s = ':21::22::24::99';
var n = '22';
findNumberInString(n, s); // true
or just use match (though test is cleaner to me)
!!s.match(':' + n + ':'); // true
Edit
Both the above use regular expressions, so a decimal ponit (.) will come to represent any character, so "4.1" will match "461" or even "4z1", so better to use a method based on String.prototype.indexOf just in case (unless you want "." to represent any character), so per Blender's comment:
function findNumberInString(num, s) {
return s.indexOf(':' + num + ':') != -1;
}
like this:
aStr = ':21::22::24::99:';
if(aStr.indexOf(':22:') != -1){
//':22:' exists in aStr
}
else{
//it doesn't
}