Ive got a really strange problem with some javascript code that ive written. I have set this code to execute on load. The idea of it is to remove a value from a text field if it is listed in another field. Here is the code:
var diseases = document.getElementById("AffectedBy").value;
var diseasearray = diseases.split("-");
alert("disease array size: " + diseasearray.length);
for (i=0;i<diseasearray.length;i++)
if (diseases.match("-" + diseasearray[i]))
{
diseasearray[i] = "-" + diseasearray[i];
alert(diseasearray[i]);
document.getElementById("DiseaseNotSelected").value=document.getElementById("DiseaseNotSelected").value.replace(diseasearray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) but when I display the values in the alert it only shows 2 values(1 blank, and 1 value)
This piece of code:
var foods = document.getElementById("FoodFor").value;
var foodarray = foods.split("-");
alert("food array size: " + foodarray.length);
for (i=0;i<foodarray.length;i++)
if (foods.match("-" + foodarray[i]))
{
foodarray[i] = "-" + foodarray[i];
alert(foodarray[i]);
document.getElementById("FoodNotSelected").value=document.getElementById("FoodNotSelected").value.replace(foodarray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) and when I display the values in the alert it only shows 3 values(1 blank, and 2 value).
Can anyone see a reason why the first code block only shows 2 items in the array as I cant see why and its really bugging me now.
the first one is running a match against a string starting with '-'.
I don't have your actual values, but let's say that the value of #AffectedBy is "test1-test2-test3".
the first alert will be 3, because the diseasearray will have three components (test1, test2, test3)
you then run through a loop (0, 1, 2).
The first one will fail, as there is no "-test1" in the string, but the other two will succeed, as there are "-test2" and "-test3" substrings.
As I said in my comment above: beware that whatever you pass into match will get turned into a regular expression. If that contains some special character, it might not match where you would expect it to (or vice versa).
The string White Spot (Ich) will be turned into the regex /White Spot (Ich)/; which does not match White Spot (Ich) but does match White Spot Ich, since the parentheses are grouping operators in a regex.
Change the regular expression test
diseases.match("-" + diseasearray[i])
into the plain string comparison
diseases.indexOf("-" + diseasearray[i]) !== -1
and you should be set.
(I think. :-)
First, for the length you need to do for example foodarray.length -1.
How many items do you have in your array (suppose to have)? We need more explanation
Related
This pertains to any language that you think will work. Is there a way to change the look of a text input to replace every second space (space as in when the space bar is hit it makes a space) i need to a way almost like a counter that once it counts 2 spaces then it replaces that 2nd space to a letter or symbol. if someone could help me with this it would be amazing and the purpose is just to change the way the text looks in this way functionality does not matter as long as it reads like normal text. ( if it helps it would be every odd number of spaces gets changed.)
for example i want to be able to copy and paste something in like this> "i went down to the sea to pick up many sticks for my collection"
and have it return something like this
i%went down%to the%sea to%pick up%many sticks%for my%collection
the end goal is for the symbol to be a different color so it stands out from the text so if that would be possible that would be amazing.
I chose javascript, but there are multiple languages that you could choose and there are multiple ways to accomplish this. This is the train of thought that you should use when solving this problem:
Determine the characters that you want to replace
Determine the character that you want to replace it with
Since we don't want to replace every single one, what is the pattern/frequency that you want to replace found occurrences with.
For the 3rd question, you've said that you want to replace every other occurrence, so we need to keep track of the count of occurrences. And replace it when occurrence modulo 2 = 1. This says replace every odd occurrence.
I chose to use regex to find all the spaces in the sentence, have a counter n and increment the counter every time I find a space.
This leaves us with the following code:
const input = "i went down to the sea to pick up many sticks for my collection";
let n = 0;
const output = input.replace(/\s/g, (m, i, og) => {
return (n++ % 2) ? m : '%';
});
// output = "i%went down%to the%sea to%pick up%many sticks%for my%collection"
Also please take a look at String.prototype.replace() so you can learn about using regex, and to learn about what the function does. This will help you learn and solve similar problems by yourself in the future.
you can use a boolean variable to count odd and even spaces and string.prototyoe.replace with a callback function:
var str = 'i went down to the sea to pick up many sticks for my collection';
var odd = true;
str = str.replace(/\s/gi, (spaceChar)=>{
odd = !odd;
return !odd ? spaceChar : '%'; // this is what you wrote (every second)
// return odd ? spaceChar : '%'; // this is what your expected result shows (every second starting with the first occurence)
});
Just as the title says...i'm trying to parse a string for example
2x + 3y
and i'm trying to get only the coefficients (i.e. 2 and 3)
I first tokenized it with space character as delimiter giving me "2x" "+" "3y"
then i parsed it again to this statement to get only the coefficients
var number = eqTokens[i].match(/(\-)?\d+/);
I tried printing the output but it gave me "2,"
why is it printing like this and how do i fix it? i tried using:
number = number.replace(/[,]/, "");
but this just gives me an error that number.replace is not a function
What's wrong with this?
> "2x + 3y".match(/-?\d+(?=[A-Za-z]+)/g)
[ '2', '3' ]
The above regex would match the numbers only if it's followed by one or more alphabets.
Match is going to return an array of every match. Since you put the optional negative in a parentheses, it's another capture group. That capture group has one term and it's optional, so it'll return an empty match in addition to your actual match.
Input 2x -> Your output: [2,undefined] which prints out as "2,"
Input -2x -> Your output: [2,-]
Remove the parentheses around the negative.
This is just for the sake of explaining why your case is breaking but personally I'd use Avinash's answer.
If you take a piece of code like this:
var string = "javascript";
var search = string.search("");
console.log(search);
and then you take this piece of code:
var string = "javascript";
var search = string.search("j");
console.log(search);
both pieces of code evaluate to 0. It's fairly annoying since I would imagine it should amount to -1 since there is no match, nothing and the. This is a problem in a script I am trying to write because these both evaluate to the exact same number even though they aren't the same value and this is making me move all my data in my .json file over by one space from this:
"heman",
"candy",
"powerpuffgirls",
"oranges"
to this:
" heman",
" candy",
" powerpuffgirls",
" oranges"
because when I test for a match from the input field the user enters to the .json data I have no way of evaluating whether the data was blank or one matching character was entered (since the javascript search method evaluates both as the same amount '0'). This incapacity of javascript to know the difference between a 'nothing' and a 'single matching char' moved along at zero index (since it's a single matching char) has forced me to move all of .json data over one space.
This feels...wrong to do, like not good practice. It's a solution but it seems like a lame one. Does anybody know any work arounds for a problem like this? Seems like a pretty simple common problem. Is there some way through this, perhaps with regular expressions or something?
Remember this:
Always, whatever be the value of the variable string (including empty string)
string.search("") = 0
So, check for length of the string!
if (string.length == 0) // Empty string
var search = query.length === 0 ? -1 : string.search(query);
I'm new to javascript and currently working my way through code school. I've done this exercise before and have no issue with it, but after not doing anything for a week i decided to go back and redo some of the exercises... now i'm stuck on this one :( here is the instructions and below that is my code... what I'm I doing wrong code school tells me I'm not adding white space between the two words?
Now alert to the screen the entire first movie in eightiesMovies, but only using the >eightiesMovies variable. For now, use the concatenation operator to unite the words into one >string. Remember to be attentive to necessary whitespace…
var movie1 = [ 16, "Candles"];
var movie2 = [ 3, "Men", "and", "a", "Baby"];
var eightiesMovies = [ movie1, movie2];
my code
alert(eightiesMovies[0,1] + " " + eightiesMovies[0,1]);
To access an array in an array, you use two sets of brackets after each other:
alert(eightiesMovies[0][0] + " " + eightiesMovies[0][1]);
(Also you were using the same item twice instead of two items.)
What's happening in your original code is that you are accidentally using the comma operator, that's why you don't just get a syntax error for that code. An expression like 0,1 will evaluate both 0 and 1, and then the value of the expression is the last value. That will make the code access eightiesMovies[1] which is an array, and the string concatenation would convert the array to a string. The result is "3,Men,and,a,Baby 3,Men,and,a,Baby" rather than the "16 Candles" that is expected.
To join the elements of an array to form a string use join()
in your example
eightiesMovies[0].join(" ");
I'm working on a grid layout function. I'm about 1/2 way there and have hit a wall.
I am using a string and running a single RegExp function per box I'm placing in the grid to determine where it will fit (based on number of rows/columns it occupies). This works successfully. Demonstration:
function findSpace(columns, rows){
var totalColumns = 4;
var grid = "11002100020000200002";
//1 represents occupied space, 0 empty space, and 2 a new line
var reg = RegExp("(0{" + columns + "})(([0-2]{" + (totalColumns - columns + 1) + "})0{"+columns+"}){" + (rows-1) + "}");
var i = grid.search(reg);
return i.index;
}
Returns the index of the match, letting me know where in my grid this box will fall. See fiddle.
I fall short trying to replace the "0"s with "1"s. Doing grid.replace(reg, "1") of course replaces everything from the beginning of the match to the end with a single "1". I need to replace just the "0"s that will be occupied for row and column, each with a "1", and not any of the characters matched between.
This is an exercise in doing things differently. Yes, I could do this with an array data structure. What fun is that? I'm not looking for a "don't do it this way do it the way everyone else does" answer, I'm trying to determine the most efficient way to solve my scenario.
Thanks!
The String#replace method might be the ticket. If you pass a regular expression and a function as the second parameter, you can dynamically manipulate each match.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace