How do I combine 2 javascript variables into a string - javascript

I would like to join a js variable together with another to create another variable name... so it would be look like;
for (i=1;i<=2;i++){
var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map,
title:"title"+i,
icon: "image"+i
});
}
and later on I have
myLatlng1=xxxxx;
myLatlng2=xxxxx;

Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!

warning! this does not work with links.
var variable = 'variable',
another = 'another';
['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)

if you want to concatenate the string representation of the values of two variables, use the + sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

Related

how do I add two variables by javascript [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
the code below concatenates the two variables instead of adding them to get one value. any help on how to correct this?
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
You can use Number() to convert values to number
function calculatetotal1() {
var mal = Number(document.getElementById('<%=txtadults.ClientID%>').value);
var child = Number(document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
Parsing both variables as float should to the trick.
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
You need to convert those values to number before adding them using the + operator. There are several ways of doing that, but you can use parseInt or parseFloat for this:
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;
You are getting input values from textbox and the datatype of textbox value by default is string. So your current code is just considering it as string and doing concatenation.
Try using parseFloat() function for both values.
Try the following code.
function calculatetotal1() {
var mal = parseFloat (document.getElementById('<%=txtadults.ClientID%>').value);
var child = parseFloat (document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
In JavaScript, + operator acts like concatenation and add the values
Like below
Var x = 2 + 3 // will be 5
Var y = '2' + 3 // will be 23 as string

How to creat a dynamic RegEx

I'm trying to match some words in a string. But I don't have a predefined number of words I need to find.
For example I search for Ubuntu 18 10 in ubuntu-18.10-desktop-amd64.iso.torrent would return true.
Or I could search for centos 7 in CentOS-7-x86_64-LiveGNOME-1804.torrent would also return true.
I don't need to check if it's lowercase or not.
What I tried :
$.get('interdit', function(data) {
var lines = data.split("\n");
$.each(lines, function(n, data_interdit) {
var url_check = $('textarea#url').val()
var split_forbidden = data_interdit.split(/[\s|,|_|.|-|:]+/);
var exist = 0;
$.each(split_forbidden, function(n, data) {
var n = url_check.search("^("+ data +")");
if(n != -1){
exist = 1
}else{
exist = 0
}
console.log('Forbidden: '+ data + ' Result: ' + n);
})
if(exist == 1){
console.log('found')
}
});
});
Sample data of the file interdit :
CentOS.7
Ubuntu-18
You want to look for existing words within the input string without the order being taken into account. You need to use positive lookaheads for this:
var search = 'Ubuntu 18 10';
var str = 'ubuntu-18.10-desktop-amd64.iso.torrent';
var re = new RegExp('^(?=.*' + search.split(/[\s,_.:-]+/).join(')(?=.*') + ')', 'i')
console.log(re.test(str));
This produces a regex as the following (with i flag set):
^(?=.*Ubuntu)(?=.*18)(?=.*10)
RegEx Array
Update
"The code give me an error jsbin.com/pecoleweyi/2/edit?js,console"
Although the question did not include unlikely input such as: *centos 7*, add the following line to escape the special characters that occur in input:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
and change the next line:
var sub = esc.replace(/\s/gi, '.');
The demo below will:
accept a string (str) to search and an array of strings (tgt) to find within the string,
.map() the array (tgt) which will run a function on each string (word)
escape any special characters:
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
replace any spaces (/\s/g) with a dot (.):
var sub = esc.replace(/\s/g, '.');
then makes a RegExp() Object so a variable can be inserted in the pattern via template literal interpolation (say that ten times fast):
var rgx = new RegExp(`${sub}`, `gim`);
uses .test() to get a boolean: found = true / not found = false
var bool = rgx.test(str);
create an Object to assign the search string: word as a property and the boolean: bool as it's value.
var obj = {
[word]: bool
};
returns an array of objects:
[{"centos 7":true},{"Ubuntu 18 10":true}]
Demo
var str = `ubuntu-18.10-desktop-amd64.iso.torrent
CentOS-7-x86_64-LiveGNOME-1804.torrent`;
var tgt = [`centos 7`, `Ubuntu 18 10`, `corn flakes`, `gnome`, `Red Hat`, `*centos 7*`];
function rgxArray(str, tgt) {
var res = tgt.map(function(word) {
var esc = word.replace(/[.*+?^${}()|[\]\\]/gi, '\\$&');
var sub = esc.replace(/\s/gi, '.');
var rgx = new RegExp(`${sub}`, `gi`);
var bool = rgx.test(str);
var obj = {
[word]: bool
};
return obj;
});
return res;
}
console.log(JSON.stringify(rgxArray(str, tgt)));

Converting Strings to Template Literals in ES6

Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

Split a variable in js or jquery

Hi I have some vars like this:
var a = Base-Shirt_Stripe.jpg
var b = Closed-Flatknit-Collar_Stripe.png
How do i create two new vars like:
var c = Base-Shirt
var d = Stripe
or
var e = Closed-Flatknit-Collar
var f = Stripe
basically split at the _ remove the _ and remove the extension.
//for example, we take a
var a = 'Base-Shirt_Stripe.jpg';
//then we take the part of a before the dot
//and split between `_`
//split returns an array
var split = a.substring(0,a.indexOf('.'))
.split('_');
//split is an array, so we use indices to indicate which
console.log(split[0]); //Base-Shirt
console.log(split[1]); //Stripe
Sample here. You can do the same for your b
may be you could do like
var a = "Base-Shirt_Stripe.jpg"
var k = a.replace(/(\.\w*)$/g, "").split("_");
alert(k[0]);
alert(k[1]);
here is the fiddle
You need to make them strings to start with, then use String.split() to split the string into an array of the different parts.
jsFiddle
var a = "Base-Shirt_Stripe.jpg"
var b = "Closed-Flatknit-Collar_Stripe.png"
var aSplit = a.substr(0, a.lastIndexOf('.')).split('_');
var c = aSplit[0];
var d = aSplit[1];
var bSplit = b.substr(0, b.lastIndexOf('.')).split('_');
e = bSplit[0];
f = bSplit[1];
You could also take the removal of the extension out into its own function using String.lastIndexOf() and String.substr().
function removeExtension(file) {
return file.substr(0, file.lastIndexOf('.'));
}
//Javascript Split can divide it into parts. Javascript Split return type is array.'
//e g.
var a = Base-Shirt_Stripe.jpg
var parts = a.split('_');
console.log(parts[0]);
//output
" Base-Shirt "
//parts[0] contain base-shirt and parts[1] contain Stripe.jpg.

Categories

Resources