I want to insert two values in one array in each loop. I have tried
feature_arr = [];
$form.find( '.variations .value' ).each( function() {
var $radios = $( this ).find( 'input[type=radio]' );
var $checked_radio = $radios.filter(':checked');
var attribute_name = $radios.attr( 'name' );
feature_arr[] = attribute_name1;
feature_arr[] = $checked_radio.val();
});
I want array this form ["1", "Brighton_Black", "2", "Frame_Base", "3", "Matching_upholstery", "6", "Headrest", "7", "Covered"]
But give me error this code
try this
var feature_arr = new Array(); // define the array or you can use feature_arr = []
and inside your condition
feature_arr.push(your_value_1);
feature_arr.push(your_value_2);
for the second part for your question in the comment try this
<html>
<head></head>
<title></title>
<style type="text/css">
</style>
<body>
</body>
<script type="text/javascript">
var thestring = "matching_upholstery";// this is your string
alert(toupper(thestring)); // in here we pass out string to the method/function we wrote that returns the converted output string. to see the result we use an alert here.
//this is the function that convert the first letter to upper and return the final result
function toupper(a)
{
var stringArray = a.split('_');//split your word from '_' character.
var firstword = stringArray[0];//get the first word
var firstwordWithupper = firstword.charAt(0).toUpperCase()+firstword.slice(1);//convert the first letter to upper
var secondword = stringArray[1]; // get the second word
var secondwordWithupper = secondword.charAt(0).toUpperCase()+secondword.slice(1);//convert the first letter of second word to upper
var finalresult = firstwordWithupper +"_"+secondwordWithupper;
return finalresult;
}
</script>
</html>
you can also do like
var a = [].concat(1,2);
in one line. In your case inside the condition you can do like
feature_arr = feature_arr.concat(value1,value2)
or if you receive your multiple data in an array this would result the same
feature_arr = feature_arr.concat([value1,value2])
Related
I have following code:
var selector="a,b,c/m,n",
property = "width,height/font-size";
I want to group each set of strings (separated by forward slash) to new array.
so I would (basically) end up with this:
var selector_array1 = [a,b,c];
var selector_array2 = [m,n];
----
var property_array1 = [width,height];
var property_array2 = [font-size];
....
so I would end up with 2 for loops (I think), like:
for(outer loop){//for each selector array
for(inner loop){//for each item in selector array apply each property in property array
}
}
Bear in mind it can only have 1 value/property like (so no forward slashes to split):
var selector="a/m",
property = "width/font-size";
or like this:
var selector="a",
property = "width";
You can still use split on the ones with no slashes. Just split once on slashes then split those results on commas.
function extractData(input) {
// Separate by /'s
return input.split('/')
.map(function(str) {
// For each of the new strings, split them on commas
return str.split(',');
});
}
var data = extractData('a,b,c/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a,b,c');
console.log(data[0].toString());
data = extractData('a/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a/width');
console.log(data[0].toString(), '|', data[1].toString());
To do that you need to use the split method of the String prototype:
var selector="a,b,c/m,n",
property = "width,height/font-size";
function splitString(s){
// Split the string with the character /
// And loop through the array
return s.split('/').map(function(stringWithComa){
// Return the result of the string split
return stringWithComa.split(',')
})
}
console.log(splitString(selector));
console.log(splitString(property));
Hope it helps ;) Dont hesitate to ask question ;)
Here is an method using split() and arrays.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var selector="a,b,c/m,n";
var property = "width,height/font-size";
var selector_array1 = new Array();
var selector_array2 = new Array();
var property_array1;
var property_array2;
var selectors = selector.split('/');
var properties = property.split('/');
for(var i = 0; i<selectors.length; i++) {
selectors[i] = selectors[i].split(',');
for(var j = 0; j<selectors[i].length;j++) {
if(i==0)
selector_array1.push(selectors[i][j])
else
selector_array2.push(selectors[i][j])
}
}
alert(selector_array1);
alert(selector_array2);
</script>
</body>
</html>
I am new to javascript and have this code which will replace the string from A to B, but if there is multiple records of As, it will only replace the first A, while the remaining will be remain as A. Note that the stringify is called twice.
"success": function(json) {
var old = JSON.stringify(json).replace('"新交易"', '"待审核"');
var newdata = JSON.parse(old);
var old = JSON.stringify(newdata).replace('"批准"', '"已充值"');
var newdata = JSON.parse(old);
fnCallback(newdata);
}
This has little to do with JSON. As documented:
To perform a global search and replace, include the g switch in the regular expression.
So change this:
replace('"新交易"', '"待审核"')
... into this:
replace(/"新交易"/g, '"待审核"')
To replace every word in your context use Regular Expressions. So check this example to see how it works:
var someText = '"新交易""新交易""新交易""新交易""新交易""新交易""新交易""新交易"';
var someText2 = '"批准""批准""批准""批准""批准""批准""批准""批准""批准""批准"';
var old = someText.replace(/"新交易"/g, '"replaced"');
var stuff = someText2.replace(/"批准"/g, '"已充值"');
https://jsfiddle.net/n1otvpy1/
I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!
I am beginner with javascript.I want to create array as 1,2,3,4,5
But I get o/p as ,1,2,3,4,5
I tried with .split() in javascript but I am not getting the required output.
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
for (a in temp ) {
temp[a] = temp[a];
}
fiddle
You could do it this way:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5",
temp = string.split('testrating_');
temp.shift(); //remove fist item which is empty
console.log(temp); //["1", "2", "3", "4", "5"]
The actual value of temp is ["","1","2","3","4","5"]. This is happening because of .split and the string starting with the delimiter.
If you always know the delimiter will be at the start of the string, you can do this, which removes the first element of the Array:
temp = string.split("testrating_").slice(1);
You can try this...
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = [];
temp = string.split("testrating_");
var tempNew=[];
for (a in temp ) {
if(temp[a]!==''){
tempNew.push(temp[a]);
}
}
alert(tempNew);
}
</script>
</body>
</html>
JSFiddle
You are getting ,1,2,3,4,5 because there is no character at the beginning of the string before testrating_ by which you are separating.
either you can remove testrating_ from first position like statement below
var str="1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_")
Or you can remove character from first index after getting result as from array
var str="testrating_1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_").slice(1);
Do this:
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
var output = new Array();
for (x = 0; x < temp.length; x++) {
output[x - 1] = temp[x];
}
alert(output);
}
</script>
</body>
</html>
You could always use .splice:
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
temp = string.split("testrating_"); // temp = ["","1","2","3","4","5"]
temp.splice(0,1) // temp = ["1","2","3","4","5"]
What splice does here is goes to the first value in the array (index #0) and removes one value from that point which would be the empty string "".
To give a little more of an explanation, you could remove the empty string and "1" by using splice like so:
temp.splice(0,2) // temp = ["2","3","4","5"]
Keep in mind that splice directly effects the array it's called upon and returns an array of values that were removed. So if you did the following:
values = temp.splice(0,2) // values=["","1"] temp=["2","3","4","5"]
Also, in this example creating a new array in the following fashion temp = new Array(); is redundant since string.split() effectively creates an array and fills it with the values that were splitted. Keep that in mind going forward. Hope this helps and welcome to the world of programming!
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
// Split and remove first entry and return an array
var final = string.split("testrating_").slice(1);
$('#out').text(JSON.stringify(final));
Try this:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.split("testrating_").join("").split("").join();
console.log(temp);
Can also be done like this:
var temp = string.replace(/testrating_/g,"").split("").join();
or just:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.match(/[\d]/g); //your regex here
console.log(temp);
Not sure about the performance though.
have tried various things
split[6].length
String.split[6].length
along these lines without success get this error message for the last one ...
ReferenceError: "string" is not defined.
Hi Thanks for all the replies, in the end I created an array based on the index of the original array and then queried the length of that. As you can see I am having trouble removing single and double quotes from the input strings. New to javascript and its making me a little crazy lol.
// Loop through all the input messages
for (var i = 0; i < input.length; i++) {
var next = output.append(input[i]);
// Get the body of the current input message
var body = input[i].text;
// Set the body
next.text = body ;
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
// Set a property
var split = next.text.split(",");
var array1 = split[5];
var array2 = split[2];
next.setProperty("aaaLength", split.length);
next.setProperty("aaaSplitValue", split.length);
next.setProperty("aaaArray1Value", split.length);
next.setProperty("aaaArray2Value", split.length);
if (next.getProperty("BaseFilename")=="name"){
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
if(split.length>10){
next.setProperty("FullFilename","nameError"+i);
next.setProperty("BaseFilename","nameError"+i);
next.setProperty("Suffix",".err");
}
if(array1.length>10){
next.setProperty("FullFilename","nameSnameSuffixError"+i);
next.setProperty("BaseFilename","nameSnameSuffixError"+i);
next.setProperty("Suffix",".err");
}
}
Length should work if the elements are strings. See the following in action at http://jsfiddle.net/46nJw/
var parts = "foo,bar,baz,foop".split(/,/);
alert( parts[3].length ); // should alert 4
var arr = ['one','two','three']
arr[1].length
returns 3
Are you sure it is returning a string?
You can force it to convert to a string like so:
String(split[6]).length;
I don't know what you need, so I give you all the options I can think of:
var commaSeparatedString = "one, two, three";
var str = commaSeparatedString.split(",");
alert (str.length) // outputs '3'
alert (str[2]); // outputs 'three'
alert (str[2].length); //outputs '5'