data = 'numbersXXXtext';
or
data = 'XXXtext';
var get = data.split('XXX');
var sum = get[1];
I would like get always "text". If data equals numbersXXXtext, the code works fine, but if data is XXXtext then get[1] is undefinded.
Does anyone know how I can solve this?
If there is only one occurrence of XXX in the string, the bit you want will always be the last item in the array returned by split. You can use pop to get the last item of an array:
var a = "numbersXXXtext";
var b = "XXXtext";
console.log(a.split('XXX').pop()); // "text"
console.log(b.split('XXX').pop()); // "text"
Try this:
var sum = get.length > 1 ? get[1] : get[0]
Strange, i just tried your code, and it's working. (http://writecodeonline.com/javascript/)
Are you sure you are not missing something?
data = 'numbersXXXtext';
//data = 'XXXtext';
var get = data.split('XXX');
document.write(get[1]);
document.write("</br>");
document.write(get);
document.write("</br>");
I didn't get undefined in neither of your strings
An alternative using substring:
var data = 'numbersXXXtext';
var value = data.substring(data.indexOf('XXX') + 'XXX'.length);
Related
I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;
localStorage.getItem() will return a string.
You need adjust your code accordingly to default to a string in case the item is not defined:
const lastScore = localStorage.getItem("latestScore") || "";
In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.
const scoreDetail = JSON.parse(lastScore) || [];
scoreDetail.push(score);
And after that convert the array into a JSON string :
localStorage.setItem("latestScore", JSON.stringify(scoreDetail));
is latest score is a obj/array/string or what?
If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array
As per the error, You are trying to apply split on an array instead of a string.
Looks like, localStorage.getItem("latestScore") is undefined while you are trying to access it and it assigned an empty array to lastScore variable.
Hence, Instead of
const lastScore = localStorage.getItem("latestScore") || [];
Use
const lastScore = localStorage.getItem("latestScore") || "";
I'm trying to figure out some collision, but the compiler keeps showing the error that .slice() is not a function. Here is the code:
var topPos1 = $('#player').css("top");
var rightPos1 = $('#player').css("right");
var topPos2 = $('#player').css("top");
var rightPos2 = $('#player').css("right");
var pos = topPos1.indexOf('px');
topPos1 = parseInt(topPos1.slice(0,pos));
My jQuery is loaded.
Maybe your topPos1 return nothing, if the $('#player') has no css value for top, assigning it to a value will result null or NaN.
You should use log the values to see if the result are correct.
you can't directly slice a number, you can convert it into string then slice after
like this:
topPos1 = parseInt(topPos1.toString().slice(0,pos));
You can just use .replace('px', '') - it will save you one function call
I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);
i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)
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'