In a Wordpress's page, the string.split is returning an array with just 1 element containing the complete string instead of splitting it into several elements.
var url = "http://127.0.0.1/?mouses=razerµs";
if (url.indexOf("?mouses=") != -1){
var mouses_substr = url.substring(url.indexOf('?mouses=') + 8);
var mouses_array = mouses_substr.split("&");
for (var i = 0; i<mouses_array.length; i++) {
alert(mouses_array[i]+"<br>");
}
}
In this case the
mouses_array
should output
razer
in the first alert box and
micros
for the second.
Instead its giving me
razerµs
There is not point using str.split since it is not splitting anything. Any fixes / workarounds?
Related
good evening, I am trying to use a single value to search an array, and return the full line the said value is in.
The Array is set up like this in string form:
Xanax,Brand,Anxiety,Code
However, now I'm stuck with calling back only the Medication, and not the full line the Medication is in, sadly. I would like to be able to grab each variable in a line, and make them their own independent variables outside of the array so I can use them for something else.
this.importDataObject("MEDDIAGNOSISICD-10.txt", "C:/Users/dell/Documents/tab
excel/MEDDIAGNOSISICD-10.txt");
var oFile = this.getDataObjectContents("MEDDIAGNOSISICD-10.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
var fileArray = cFile.split('\t');
var Med = this.getField("Medications 1");
var Index = fileArray.indexOf(Med.value);
var Call = fileArray[Index];
console.println(Call);
Any help would be wonderful!
It's because you are running the indexOf method on the whole array, you need to run it on the each value instead. Try a for loop before you check IndexOf method.
Like this:
var i, Index;
for (i = 0; i < fileArray.length; i++) {
Index = fileArray[i].indexOf(Med.value);
if(Index > -1) console.log('Your search is found in ' + fileArray[i] );
}
Note that, in here the variable Index will be 0 or larger if that search is successful. And will be of value -1 if no match is found.
i have a bug in this code that i cannot seem to solve. if there is only 1 instance of Act, it works as it should. But when there is more than 1 instance of Act, it breaks. Not sure what I am missing here.
//Find all instances of italics
var findItalics = new RegExp(/(<em>.*?<\/em>)/g);
var italicsArray = [];
var italicCount;
while (italicCount = findItalics.exec(searchInput)) {
italicsArray.push(italicCount[0]);
}
//Find the italics containing the word 'Act'
var keywordItalics = new RegExp(/<em>.*?(Act).*?<\/em>/g);
var keywordItalicArray = [];
var italicCountKeyword;
while (italicCountKeyword = keywordItalics.exec(italicsArray)) {
keywordItalicArray.push(italicCountKeyword[0]);
}
//Remove all instances of the keyword(s)
for (var tlcs = italicsArray.length - 1; tlcs >= 0; tlcs--) {
if(italicsArray[tlcs] == keywordItalicArray) {
italicsArray.splice(tlcs, 1);
}
}
Thanks to #artgb who helped me rethink this.
//Find all instances of italics
var findItalics = new RegExp(/(<em>.*?<\/em>)/g);
var italicsArray = [];
var italicCount;
while (italicCount = findItalics.exec(searchInput)) {
italicsArray.push(italicCount[0]);
}
//Find the italics containing the word 'Act'
var keywordItalics = new RegExp(/<em>.*?(Act).*?<\/em>/g);
var keywordItalicArray = [];
var italicCountKeyword;
while (italicCountKeyword = keywordItalics.exec(searchInput)) {
keywordItalicArray.push(italicCountKeyword[0]);
}
//Remove all instances of the keyword(s)
for(var xXx = 0; xXx < keywordItalicArray.length; xXx++){
for (var tlcs = italicsArray.length - 1; tlcs >= 0; tlcs--) {
if(italicsArray[tlcs] == keywordItalicArray[xXx]) {
italicsArray.splice(tlcs, 1);
}
}
}
var keywordItalics = new RegExp(/<em>.*?(Act).*?<\/em>/g);
Should usually be shortened to:
var keywordItalics = /<em>.*?(Act).*?<\/em>/g;
Where your () are, this would only get a capture of "Act", so to capture whole string in the em, it should be:
var keywordItalics = /<em>(.*?Act.*?)<\/em>/g;
However, a faster way (without regexp) you could get an array of all the emphasized tags just by:
var keywordItalics = document.getElementsByTagName('em');
If you're just trying to get rid of all em's containing "Act", all you should need is:
document.body.innerHTML = document.body.innerHTML.replace(
/<em>.*?Act.*?<\/em>/g,
''
);
This should remove all traces of em's containing "Act" in the document (effectively replacing those strings with an empty string, aka nothing). It will cause a reflow, however. If they are inside a containing element besides body, would be better to get containing element first (instead of using body). There are "better" ways of doing this, but this is probably simplest coding-wise.
Update: an easy way to remove em's with "Act" from the array would be:
italicsArray = italicsArray
.join('_SEP_') // Convert to string
.replace(/<em>.*?Act.*?<\/em>/g,'') // Delete matched entries
.replace(/(_SEP_)+/g,'_SEP_') // Collapse multiple seperators
.split('_SEP_') // Convert back to array
;
This basically uses a seperator _SEP_ (to avoid collisions with strings containing ',') and turns the array into a string, deletes all matches to your regexp, removes what would become undefined entries, and recreates the array in the same name.
First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
I'm a beginner with javascript, and after searching I am still running into an error with this part of my code.
I have an array:
var choices = [ '$5/hr', '$6/hr', '$7/hr', '$10/hr' ];
And I want to use a regular expression to return the array as integers so I can use it for further calculations. I know that replace only works on strings and not an array so I have tried the following:
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
EDIT: Apparently the issue is somewhere else in my code. Maybe this needs to be wrapped in another function?
Here is the function that this resides in. This function receives an array as a value and will calculate an average using the array received and the choices array which I cannot convert to integers.
// Choice values
var ul = document.getElementById('Results');
var choices = [];
// Get li element choices
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
choices.push(ul.childNodes[i]);
}
}
// Strip the last element in array since it is the result container.
choices.splice(-1,1);
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
Thanks!
The issue is that you are pushing the nodes in your array, not their text content. Try this instead:
choices.push(ul.childNodes[i].textContent)
or:
choices.push(ul.childNodes[i].childNodes[0].nodeValue)
I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.