Compare two variable string in JavaScript - javascript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?

You might want to try the following
var s = statuss.toString().trim();

The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

Related

Make javascript as function

i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

variable string appearing as undefined, new string not appearing in array, javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Unable to compare two Strings in javascript

I am trying two compare two strings in JavaScript. But I guess there is some problem while comparing. It doesn't show the results.
if(ajaxRequest.readyState == 4){
var msg = ajaxRequest.responseText;
var fld = document.getElementById("prtCnt");
if(msg == "false") {
var msg = "This User Name is already taken !!!!";
fld.className = "bp_invalid";
// fld.style.color=green;
fld.innerHTML=msg;
}
Can any body tell me where the problem is? Thanks.
You might want to check if there's any space before or after the "false" string that you return from the server. You can do it easily with this:
alert('"' + msg + '"');
If there is extra space, you can just do:
msg = msg.trim();
and then do your if statement
Ensure that there is no white space around the word "false" with something like:
if( msg.match(/\s*false\s*/i) )

Javascript say if a folder is child of another

I have these strings which are addresses of files and folder:
../../../folder1/sub1/sub12/
../../../folder1/
../../../another-folder/
I want to compare them using javascript - possibily jquery - to see if for example string 1 have a part egual to string 2 but something more saying that string 1 is child of string 2.
How can i do this?
you could try something like the following
var path1 = "../../../folder1/";
var path2 = "../../../folder1/sub1/sub12/";
if (path2.indexOf(path1) != -1){
//path2 is a sub of path 1
}
In case your string can contain also absolute paths or paths containing .. not only at the beginning I would recommend checking if .indexOf return 0 instead of anything that is not -1.
It can help with cases like.
var path1 = "/rootFolder/";
var path2 = "../folder/rootFolder/";
if (path2.indexOf(path1) === 0) {
console.log("You want this"); // won't get executed => good
}
if (path2.indexOf(path1) !=-1) {
console.log("You don't want this"); // will get executed => bad
}
if(string1.indexOf(string2) != -1){
//string2 is present in string1
}
else{
//string2 is not present in string1
}
You can use the indexOf method to find whether one string is a part of another string.
From w3schools documentation:
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
var test = "../folder/subfolder1";
var test2 = "../folder";
if (test.indexOf(test2) !=-1) {
alert(test + " is a subfolder of " + test2);
}

Categories