I have this simple div:
<div id='names'>
name1[John]
name2[Blake]
name3[Sven]
name4[Ellis]
</div>
And I want to return these variables using JavaScript
var name1 = "John";
var name2 = "Blake";
var name3 = "Sven";
var name4 = "Ellis";
Your question lacks a lot of detail. Can there be more than those four names? Can't you restructure your code to get an easier access to the data?
var toParse = document.getElementById('names').innerHTML;
var m;
var re = /\[(.*)\]/g;
while (m = re.exec(toParse)) {
console.log(m[1]);
}
(https://jsfiddle.net/hL4bu5j1/)
This code looks for text in [Bracers] and outputs it to the console to give you an idea how you could approach this. You should be good to go with that. Wanted to put this as a comment but I'm not yet allowed to.
This should do it:
//document.body.innerHTML = "<div id='names'>\n name1[John]\n name2[Blake]\n name3[Sven]\n name4[Ellis]\n</div";
var obj = {};
var str = document.getElementById("names").innerHTML;
while(str.lastIndexOf(' ') >= 0) {
str=str.replace(' ','')
}
var str=str.split("\n");
for(var i = 0;i<str.length;i++){
if(str[i].length > 2) {
obj[str[i].replace(']','').split('[')[0]] = str[i].replace(']','').split('[')[1];
}
}
console.log(obj)
Here an ugly version :
var divContent = document.getElementById('names').innerHTML;
var array = divContent.trim().split(" ").filter(removeEmpty);
console.log(array)
var name1 = array[0].split('1')[1];
I think Regex suits better for your issue
https://jsfiddle.net/hrgk2s1u/
Related
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
Hi i'm new to Jquery...any help is appreciated.
Using above API path data how can we generate URL like given below using JQuery?
Thanks in advance....
Result:
/self/GHUYFUYI/my/12346
var api = "/self/{0}/my/{1}";
var array = new Array("GHUYFUYI",12345);
for (var i = 0; i < array.length; i++) {
api = api.replace("{"+i+"}",arr[i]);
}
cosole.log(api);
you can do something like this.
You don't need jQuery for this. Just plain old Javascript...
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
api = api.replace("{code}", code).replace("{id}", id);
Your best bet would be to use regular expressions. Here's a simple example:
var api = "/self/{code}/my/{id}";
var code = "GHUYFUYI";
var id = 12346;
api = api.replace(/{code}/, code).replace(/{id}/, id);
You can use the javascript function Replace (http://www.w3schools.com/jsref/jsref_replace.asp)
api = api.replace("{code}", code).replace("{id}", id);
Enhance string prototype
if (!String.prototype.format) {
String.prototype.format = function() {
var str = this.toString();
if (!arguments.length)
return str;
var args = typeof arguments[0],
args = (("string" == args || "number" == args) ? arguments : arguments[0]);
for (arg in args)
str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
return str;
}
}
Usage
var formatData = {
code:"GHUYFUYI",
id:12346
};
var api = "/self/{code}/my/{id}".format(formatData);
Credits: Gabriel Nahmias
I want to get this (four keys & values in one object):
[{"sms":"Y","email":"Y","phone":"Y","oto":"Y"},{"sms":"N","email":"N","phone":"N","oto":"N"}]
but this is result :
[{"sms":"Y"},{"email":"Y"},{"phone":"Y"},{"oto":"Y"},{"sms":"N"},{"email":"N"},{"phone":"N"},{"oto":"N"}]
here is my code:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk = 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
Can you please show us the form as well? This gives a limited scope to answer.
But If i guess right, you have a form wherein you have the following fields sms, email, phone, and then oto, right?
So what you have to do is, instead of doing it for each input, you have to do it once for the four inputs.
Meaning that you have to set chkObj['sms'], chkObj['email'], chkObj['phone'], and then chkObj['oto'] and then do chkArray.push(chkObj).
You missed the second equals sign in this expression:
if(cntchk = 4){, so instead of comparison there is an assignment. Change this to if(cntchk == 4){
You have missed one "=" sign in if condition.
try this:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk **==** 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
I have the following
var invest401_2 = $("input[type=hidden][name=invest401_2]").val();
var invest401_3 = $("input[type=hidden][name=invest401_3]").val();
var invest401_4 = $("input[type=hidden][name=invest401_4]").val();
var invest401_5 = $("input[type=hidden][name=invest401_5]").val();
var invest401_0label = Math.round(((invest401_0/balance401)* percent401kb));
var invest401_1label = Math.round(((invest401_1/balance401)* percent401kb));
var invest401_2label = Math.round(((invest401_2/balance401)* percent401kb));
var invest401_3label = Math.round(((invest401_3/balance401)* percent401kb));
var invest401_4label = Math.round(((invest401_4/balance401)* percent401kb));
var invest401_5label = Math.round(((invest401_5/balance401)* percent401kb));
$("#invest401_0").text(invest401_0label+'%');
$("#invest401_1").text(invest401_1label+'%');
$("#invest401_2").text(invest401_2label+'%');
$("#invest401_3").text(invest401_3label+'%');
$("#invest401_4").text(invest401_4label+'%');
$("#invest401_5").text(invest401_5label+'%');
Having the count total - ex. 5
How do a throw this into a for each loop.
I tried but didnt work.
Try this
var invest401_label = [];
var invest401 = [];
for(i=0;i<6;i++)
{
invest401[i] = var invest401_2 = $("input[type=hidden][name=invest401_"+i+"]").val();
invest401_label[i] = Math.round(((invest401[i]/balance401)* percent401kb));
$("#invest401_"+i).text(invest401_label[i]+'%');
}
Take a look at $.each.
http://api.jquery.com/jQuery.each/
If you add a class to this elements $("input[type=hidden][name=invest401_2]").val(); you can get them as an array and use each.
If you add a class named elements. Use the following example.
$('.elements').each(function(i, element) {
var invest = $(element).val();
$(element).val(Math.round((invest/balance401)* percent401kb));
});
Or
var $elements = $('.elements');
for(var i in $elements) {
var element = $elements[i];
element.val(Math.round((element.val()/balance401)* percent401kb));
}
Assuming there is only #invest401_0 - 5
$("[id=^invest401_]").each(function(){
$(this).text(Math.round((($("input[type=hidden][name="+this.id+"]").val()/balance401)* percent401kb))+'%');
});
Reference
http://api.jquery.com/jQuery.each/
http://api.jquery.com/category/selectors/
Although this may not work ( I'm currently writing this from an ie8 machine) this /should/ do what you want correctly and replaces all of the code you have there
for (i = 0; i < $('.hiddenelems').size(); i++) {
$('.hiddenelems:eq('+i+')').text(Math.round((($('.hiddenelems:eq('+i+')').val()/balance401)* percent401kb))+'%');
}
I'm unable to read regex.
Let's say we have this string: "mydomain.bu.pu" and I want to grab the ".bu.pu" part of it;
I'm thinking about using something like:
indexOf and later substr ... But I confess I'm kind of lost...
Any help please? :D
Thanks in advance,
MEM
var afterDot = str.substr(str.indexOf('.'));
The above answers include the dot in the string. If you only want what's after the dot:
var afterDot = str.substr( str.indexOf('.') + 1 );
s = s.substring(s.indexOf("."));
That should do the trick.
Here is the three simple way I know.
const text = "Allah is great. Allah is only one"
const methodOne = text.split('.');
console.log(methodOne[0]); // BEFORE DOT
console.log(methodOne[1]);
const methodTwo = text.slice(text.indexOf('.')+1);
console.log(methodTwo);
const methodThree = text.substring(text.indexOf(".")+1);
console.log(methodThree)
sixCommaTwoValidation method for numeric 6,2 validation and restiction.
var afterDot = '';
var beforeDots = inputValue.split('.');
var beforeDot = beforeDots[0];
if(beforeDots[1]){
var afterDot = beforeDots[1];
if(afterDot.length > 3 ){
afterDot = afterDot.slice(0, 2);
}
afterDot = '.'+ afterDot;
}
if(beforeDot){
if(beforeDot.length > 6 ){
beforeDot = beforeDot.slice(0, 6);
}
if(beforeDots[1] == ''){
beforeDot = beforeDot + '.';
}
}
inputValue = beforeDot + afterDot;
return inputValue;
maybe this is too late to consider, but this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
lkjasdf_alksjd_ksdf.jpg = ksdf.jpg
aaa_bbb_ccc.jpg = ccc.jpg
testing_image.jpg = image.jpg
You could just replate '_' to '.'
I hope someone can help me with the following...
I have this code below it is written in classic asp and javascript...
I have this variable in the code below my2String1 how can I make this a dynamic variable like:
my2String1_1
my2String1_2
my2String1_3
I have a database value Recordset2.Fields.Item("article_no").Value which could be the dynamic value like:
my2String1_Recordset2.Fields.Item("article_no").Value (which should do the trick) but I am not sure how to implement it...
while((Repeat1__numRows-- != 0) && (!Recordset2.EOF)) {
var my2String1 = ""+(Recordset2.Fields.Item("article_description").Value)+"";
my2String = my2String1;
var my2regexp = new RegExp(checkduplicates, "ig");
my2Array = my2String1.match(my2regexp);
my2length = my2Array.length;
for (i = 0; i < my2length; i++) {
my2Array[i] = '\''+my2Array[i]+'\'';
}
var arr = (myArray+my2Array).split(',');
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
Repeat1__index++;
Recordset2.MoveNext();
}
If you have any ideas on how to solve this please help me
I'm going to ignore that load of code because it clouding the issue. The feature of JScript you are looking to for is the ability to create named properties on an object:-
var myDescriptions = {}
var name = "Test"
var description = "This is a test"
myDescriptions[name] = description;
Response.Write(myDescriptions[name]);
Would send "This is a test" to the response.