how to get javascript variable value in different variable [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have 2-9 value stored in a single variable in JavaScript.
But I want 2 to be stored in a variable and 9 stored in b variable.
For example :
<script>
var a = "2-9";
</script>
And I want to,
<script>
var a = "2";
var b = "9";
</script>
Please help me.

You could use the charAt() method of String in javascript.
var a = string.charAt(0);
var b = string.charAt(2);
where string is "2-9".
I suppose that your string, wouldn't have the form "2-10", because in this case that will not work.
If that's the case then you have to use the split() method of String in javascript.
var c = string.split('-');
var a = c[0];
var b = c[1];
For futher documentation about these methods in javascript plese refer to the following links:
JavaScript String charAt() Method
JavaScript String split() Method

use .split() in javascript
var a = "2-9";
var c = a.split("-");
a = c[0]; // it returns 2
var b = c[1]; // it returns 9

You can use .split():
The split() method splits a String object into an array of strings by
separating the string into substrings.
var a = "2-9",
b = a.split('-')[1];
a = a.split('-')[0];
Fiddle Demo

What you can do is this:
<script>
var string_value = "2-9".split('-'),
minimum_name = string_value[0], // 2
maximum_name = string_value[1]; // 9
</script>
Make use of .split() which creates an array out of a string, so you can split it by - then you can assign the values with their indexes like [0], [1].

Related

Remove second part of string with split() [duplicate]

This question already has answers here:
How to remove part of a string?
(7 answers)
Closed 10 months ago.
I have a variable with a string, let's say this one, which I then display on a page on the site:
let value = "qwe asd — bensound summer";
document.getElementById("text").innerHTML = value;
And I want to remove its second part when displaying this line on the page bensound summer along with a dash —.
And in order to receive only the first part, which is before the dash, when displayed on the page, in the form: qwe asd.
I read about str.split() but didn't find anything like it and didn't quite understand how it all works.
Use the split method
let value = "qwe asd - bensound summer";
value = value.split('-')[0] //
document.getElementById("text").innerHTML = value;
You can use it like this:
let value = "qwe asd — bensound summer";
let splittedString = value.split("-");
document.getElementById("text").innerHTML = splittedString[0];
Hope, it helps!!

Javascript: Remove letters outside of two parentesis [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, hello. I edited the entire thing.
app.get('/', async (req, res) => {
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
//var resultsConverted = results.toString();
//let resultsFinal = resultsConverted.split('"');
console.log(results)
res.render('index.ejs', { startText: results });
})
In the above code I want to only keep the second part of it specified better in this image: https://i.stack.imgur.com/Wi031.png
I want to create a variable containing the following:
Hello, and welcome to my website. I don't know how you found me but yo...
I already have a constant containing the search results, but it is this:
[
{
_id: 6047667ff156cb8135bdaa88,
mainPage: "Hello, and welcome to my website. I don't know how you found me but you're welcome :)."
}
]
Thanks for the understanding :)
a = a.split("\"")[1]
If you mean extracting what's inside double quotations, you have two methods:
1 - Use Regular Expressions:
You can use regular expression /.*"(.*)".*/ which tries to capture everything inside parentheses. You can use exec method. like :
const importantPart = /.*"(.*)".*/.exec(a)[1] (a is your variable)
2 - Using indexOf string methods
In JavaScript strings have two useful methods: indexOf and lastIndexOf. In addition to a substring.
You can use these to extract the important part:
a.substring(a.indexOf('"') + 1, a.lastIndexOf('"'))
There are several solutions. One could be:
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let a_splitted = a.split('"');
console.log(a_splitted[1]);
You can use regular expressions to extract the part that you need.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let result = a.match(/\"(.*)\"/);
console.log(result[1]);
There are a lot of what-ifs though.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let regex = /(?<=\")(.*?)(?=\")/;
let result = regex.exec(a)[0];
console.log(result);

How to get a number from HTML form and pass it to JavaScript? [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 7 years ago.
I am trying to calculate Body Mass Index by receiving Weight and Height from HTML form and passing it to JavaScript code by .getElementById();. But, as far as I understand, type of data received from form is "string" and I need to receive a "number". How can I solve this problem?
Use parseInt().
var a = "10";
var b = parseInt(a);
See : http://www.w3schools.com/jsref/jsref_parseint.asp
var a = document.getElementById("whatever").value;
// You can use any 3
+a; // Unary Operator
parseInt(a, 10); // parseInt with radix 10
Number(a);
you can use function parseInt(string) that Convert string into int .Now in your senario :-
var weight_str = document.getElementByID("weight");
var weight_int = parseInt(weight_str);
this will give you the result.

converting python code to javascript code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');

Converting string to array object using javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I convert the following string using JavaScript to array:
from: var x = "{id:'2'},{name:'code,Barer'}";
to: var x1 = [{id:"2"},{name:"code,Barer"}];
If you want that exact string to be an array object you can do this:
var x = "{id:'2'},{name:'code,Barer'}";
var newArray = eval("[" + x + "]");
Here are some the dangers of eval: Why is using the JavaScript eval function a bad idea?
How are you getting the variable x? If you can get whatever it is to spit out valid JSON (using JSON.stringify or something similar) you can then parse it correctly into JS (although some implementations of JSON parsers do use eval).
If you want to avoid using eval for security reasons try this
var string = "{id:'2'},{name:'code,Barer'}",
array = string.substr(1, string.length - 2)
.split("},{")
.map(function(item){
item = item.split(":");
var result = {},
name = item[0],
value = item[1].replace(/'/g, "");
result[name] = value;
return result
});

Categories