replace gives different result on same string? - javascript

Why replace function gives different results on the same string? The only difference I see is whether the string is in a variable or is a literal?
I am trying this in node REPL:
> "2015/05/21 23:59:59".replace(/^[0-9]/g, '')
'015/05/21 23:59:59'
> var time = "2015/05/21 23:59:59"
> time.replace(/[^0-9]/g, '')
'20150521235959'

Related

Global variable is null [duplicate]

This question already has answers here:
JavaScript String concatenation behavior with null or undefined values
(7 answers)
Closed 6 years ago.
I have a global variable. The variable is equal to null. var a=null; Then I write a=a+"example" in console. But output is null example. Why is it so ?
There are three possibilities in javascript:
Option 1
var a;
a=a+"example";
output: "undefinedexample"
Option 2
var a=null;
a=a+"example";
output: "nullexample"
Option 3
var a="";
a=a+"example";
output: "example"
As per your Question you need to define third option. bcz in javascript null and "" both are different types.
For more ref JavaScript String concatenation behavior with null or undefined values
If You want to concatenate strings this way, You shouldn't assign null but an empty string. Value null will be changed to string 'null' in your code. Example:
var a = '';
for(var i=0; i<10; i++) {
a = a + 'abc';
}
As you are concatenating it with string it turning out to be string see this example it adopts the datatype you assign it to be for the initial value was null
if you concat with string it takes string type if number then with number type and so on
var s = null;
console.log(s+"example");
console.log(s+5);
console.log(s+17.5)
I don't know what u really expecting,according to your problem,i think you need to concatenate two string,if am correct you can use
var str1 = '';
var str2 = "example";
var res = str1.concat(str2);
instead of null you can use ''

Checking if the first character of a string is a number gives an error that charat is not a valid method

I have a method that validates a field against 3 regex expressions and returns an error based on which expression failed.
function mfpValidateValue()
{
var pCtrl = window.document.forms[0].txtValue;
var pStrValue = mTrim(pCtrl.value);
if (pStrValue == '')
return true;
var regexNum = new RegExp("^[0-9]{9}.{0,3}$"); // First 9 are numeric followed by up to any 3 characters
var regexLetter1 = new RegExp("^[A-Z]{1,3}[0-9]{6}$"); //Up to the first 3 are alpha, then there are exactly 6 numbers
var regexLetter2 = new RegExp("^[A-Z]{1,3}[0-9]{9}$"); //Up to the first 3 are alpha, then there are exactly 9 numbers
var error = "";
// If any of the RegEx fails, set base error message
if (!regexNum.test(pStrValue) || !regexLetter1.test(pStrValue) || !regexLetter2.test(pStrValue))
error = "Please enter a valid Value.";
// Set more specific error message.
if (!isNaN(pStrValue.charat(0)))
error += " If the first character of Value is a digit, then the first nine characters must be digits.";
else
error += " If the first character of Value is a letter, up to the first three characters must be letters proceeded by 6 or 9 digits.";
return (error == "");
}
I get the following error message on this line:
if (!isNaN(pStrValue.charat(0)))
Object doesn't support property or method 'charat'
And the value in pStrValue is:
"12345678"
Is JavaScript using the term "object" ambiguously here to refer to my particular variable, or does it actually think pStrValue is an object and not a string?
You have a minor mistake. charat() is not a function, but charAt() is.
Your code should be
if (!isNaN(pStrValue.charAt(0)))
Here is the function
http://www.w3schools.com/jsref/jsref_charat.asp
You check this:
if not is Not a Number
The new ECMAScript 2015 (ES6) has a new method:
Number.isInteger(value)
Mozilla Developer Network describes:
If the target value is an integer, return true, otherwise return false. If the value is NaN or infinite, return false.
See full information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
A proper alternative is:
if (Number.isInteger(parseInt(pStrValue.charAt(0))))

unexpected results in evaluation of chains logical expressions javascript

I am writing a program to identify special numbers according to the criteria laid out in this code wars kata:
http://www.codewars.com/kata/catching-car-mileage-numbers
Here is a link to my full code and tests:
http://www.codeshare.io/UeXhW
I have unit tested my functions which test for each of the special number conditions and they appear to be working as expected. However, I have a function:
function allTests(number, awesomePhrases){
var num = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros(num) || sameDigits(num) || incrementing(num) || decrementing(num) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
which determines if any of the criteria of being a special number is met and that's not working as expected. For example, when I tested the allZeros() function on 7000 it returned true, but alltests(7000) is returning false. Is there something about how chains of logical expressions are evaluated that I don't understand or is the problem something else?
I have looked at W3schools and MDN to try and diagnose the problem.
Change all your !== to != will do.
False results as long as allTests() executes with a second argument even it it's the empty string, as follows:
allTests(7000,"");
If the function is called with just one argument, i.e. the number, expect this error:
Uncaught TypeError: Cannot read property 'length' of undefined
The error message refers to one of the functions in the logic chain, namely matchPhrase() which expects two parameters: number and awesomePhrases. If instead of providing an empty string, you use null, you'll also get the same error message.
JavaScript doesn't support the concept of default parameters -- at least not in a way that one might expect; the parameters default to undefined. But there is a way to work around this hurdle and improve the code so that one may avoid this needless error. Just change matchPhrase() as follows:
function matchPhrase(number, awesomePhrases){
awesomePhrases = typeof awesomePhrases !== 'undefined' ? awesomePhrases : "";
for(var i = 0, max=awesomePhrases.length; i < max; i++){
if(number == awesomePhrases[i]){
return true;
}
}
return false;
}
The first statement accepts the second argument's value as long as it is not the undefined value; if so, then the variable gets set to the empty string. (Source for technique: here).
To make the code more readily comprehensible, I suggest rewriting allTests() as follows, so that the code follows a more explicit self-documenting style:
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
// if any criteria is met and the number is >99 return true
return number > 99 && (allZeros( arrDigits ) || sameDigits( arrDigits ) || incrementing( arrDigits ) || decrementing( arrDigits) || palindrome(number) || matchPhrase(number, awesomePhrases)) ? true : false;
}
This function takes a number and uses its toString() method to convert the number to a string. The resulting string which is not visible will split itself on the empty string so that the result of arrDigits is an array of numerical strings, each one consisting of just one digit. This is the point of origin for the ensuing problem with allZeros() which compares a stringified digit with a number.
Incidentally, in the function allTests() there is an awfully lengthy ternary expression. The syntax is fine, but you might wish to rewrite the code as follows:
function getCriteriaStatus(arrDigits,number,awesomePhrases) {
var criteria = new Array();
criteria[0] = allZeros( arrDigits );
criteria[1] = sameDigits( arrDigits );
criteria[2] = incrementing( arrDigits );
criteria[3] = decrementing( arrDigits);
criteria[4] = palindrome(number);
criteria[5] = matchPhrase(number, awesomePhrases);
var retval = false;
for (var i=0, max=6; i < max; i++) {
if ( criteria[i] == true ) {
retval = true;
break;
}
}
return retval;
}
function allTests(number, awesomePhrases){
var arrDigits = number.toString().split('');
var criteria_met = getCriteriaStatus(arrDigits,number,awesomePhrases);
return (number > 99 && criteria_met);
}
To obtain the desired true result from allTests() when it invokes allZeros(), rather than complicate the code by using parseInt(), I suggest rewriting allZeros() and any other functions containing code that compares a numerical string value with a number by changing from the identity operator to the equality operator. The change involves merely replacing === with == as well as replacing !== with !=. The code that compares values of the same data type, using the identity operators, those operators may, and probably should, remain unchanged. (See here).

String compare in JavaScript

Can anybody help me to do string compare(means not string to string as such, the values are fetched from object and stored in variable and comparing variable to variable, variable to variable) in the JavaScript.
var val = findObject(":text1").text;
var real = findObject(":text2").text;
if (real.search(val) > 0) // if(real.indextOf(val) > -1) {
test.log("Pass");
}
else {
test.log("fail");
}
You should be able to achieve that by using the === operator
var val = findObject(":text1").text;
var real = findObject(":text2").text;
if (real === val) // if(real.indextOf(val) > -1)
{
test.log("Pass");
}
else
{
test.log("fail");
}
The === operator performs value as well as the type checking
Just compare them as follows
if (val === real){
}
else
{
}
If you know that both types are string you can also use '==' instead of '==='
Checking for exact same values is made by:
When comparing only values
==
When comparing values and types
===
When you want to check if y is a substring inside x string.
x.indexOf(y) > -1
I would recommend trim input before comparing (if that won't mess with business logic).
Like so:
var val = findObject(":text1").text.trim();
This will remove all not necesary spaces and white characters, that could be sometimes troublesome.

Check a string that MUST contain another string [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I want to check if string b is completely contained in string a.
I tried:
var a = "helloworld";
var b = "wold";
if(a.indexOf(b)) {
document.write('yes');
} else {
document.write('no');
}
The output is yes, it is not my expected output, because string b(wold) is not completely contained in string a(helloworld) --- wold v.s. world
Any suggestion to check the string?
Read the documentation: MDC String.indexOf :)
indexOf returns the index the match was found. This may be 0 (which means "found at the beginning of string") and 0 is a falsy value.
indexOf will return -1 if the needle was not found (and -1 is a truthy value). Thus the logic on the test needs to be adjusted to work using these return codes. String found (at beginning or elsewhere): index >= 0 or index > -1 or index != -1; String not found: index < 0 or index == -1.
Happy coding.
You need to use if(a.indexOf(b) > -1) instead. indexOf returns -1 when it can't find a string.
.indexOf returns -1 if no match was found, which is a truthy value. You'll need to check more explicitly:
if (a.indexOf(b) != -1)
That's because indexOf returns -1 if a value is not found:
if(a.indexOf(b) != -1) {
you may want to use this
if(a.indexOf(b) != -1)
You need to test if the result is -1. -1 indicates no match, but evaluates to true in a boolean sense.
var a = "helloworld";
var b = "wold";
if(a.indexOf(b) > -1) {
document.write('yes');
} else {
document.write('no');
}

Categories

Resources