Everythink in between / and / will printable in javascript....! why? - javascript

Why everything between / and / is going to print? It should give me error in console.
console.log normally print string enclosed within "" or any variable and object, in below case i am not passing string or any variable and object, but still it is printable.
var x = 10;
console.log(/m/);
console.log(/c/);
console.log(/&/);
console.log(/var/);
console.log(/x/);

Anything between / and / is considered to be regex. So, that's why it prints them out.
If you do a console.log( typeof /test/ ); it'll say Object which means that it is something.
JavaScript allows you to use the RegExp short hand like - /test/ which will match the string test in any given sequence.
Try something like:
let testOne = /test/;
let testTwo = new RegExp( 'test' );
console.log( testOne.test( 'test' ) );
console.log( testTwo.test( 'test' ) );
the code will output:
true
true
P.S.: The function regExp.test( String ) returns true if the String inside matches the expression defined in the regExp object.

Related

Split string, get second half

I need to split a string, but grab the second half of the string...
var str = "How, are, you, doing, today?";
var res = str.split(",", 3);
console.log(res);
Returns "How,are,you." How can I get "doing,today?"?
Perhaps split() isn't the best way? All I would like is to do is essentially split the string in half and get both values as different variables.
You can use split to get all values (by not passing a number to it), and then use slice to get values from index 3 to the end of the list of values:
var str = "How, are, you, doing, today?";
var res = str.split(",").slice(3);
console.log(res);
If you don't know what the length of your CSV string will be, you could:
const get2ndHalf = (csv, del = ',') => {
const arr = csv.split(del);
return arr.slice(Math.ceil(arr.length / 2)).join(del).trim();
}
console.log( get2ndHalf("How, are, you, doing, today?") )
console.log( get2ndHalf("This; one; is; a; tiny; bit; longer!", ";") ) // using delimiter ;
console.log( get2ndHalf("One") ) // Hummmm maybe rather Math.floor instead of math.ceil!
Or even better, to prevent empty results (like in the example above) use Math.floor
const get2ndHalf = (csv, del = ',') => {
const arr = csv.split(del);
return arr.slice(Math.floor(arr.length / 2)).join(del).trim();
}
console.log( get2ndHalf("How, are, you, doing, today?") )
console.log( get2ndHalf("This; one; is; a; tiny; bit; longer!", ";") ) // using delimiter ;
console.log( get2ndHalf("One") ) // Now this one is legit!

How to detect star sign "*" in regex?

Below is my code..
/(?!\*)/.test("test*test")
The result still return true.
I want to validate the string which will return false if any * in string.
Something is wrong with code?
Your regex returns true because it matches the starting position. The test you have just says "is there a position that is not followed by a *?" which literally any string will match - even "*" matches because after the * there is a position that is not followed by a(nother) *.
If you want to test if a string does not contain a *, the simplest solution is:
"test*test".indexOf("*") < 0 // true if no * in string
Doing so with regex would be something like:
/^[^*]*$/.test("test*test")
But that's more work.
Simply test for presence of * and negate the output
var string="123*456";
console.log( !(/\*/.test(string)) );
false
var string="12*34*56";
console.log( !(/\*/.test(string)) );
false
var string="123456";
console.log( !(/\*/.test(string)) );
true

Unexpected behavior of regexp in JavaScript

I've encountered this weird behavior:
I'm on a breakpoint (variables don't change). At the console you can see, that each time I try to evaluate regexp methods on the same unchanging variable "text" I get these opposite responses. Is there an explanation for such thing?
The relevant code is here:
this.singleRe = /<\$([\s\S]*?)>/g;
while( this.singleRe.test( text ) ){
match = this.singleRe.exec( text );
result = "";
if( match ){
result = match[ 1 ].indexOf( "." ) != -1 ? eval( "obj." + match[ 1 ] ) : eval( "value." + match[ 1 ] );
}
text = text.replace( this.singleRe , result );
}
When you use regex with exec() and a global flag - g, a cursor is changing each time, like here:
var re = /\w/g;
var s = 'Hello regex world!'
re.exec(s); // => ['H']
re.exec(s); // => ['e']
re.exec(s); // => ['l']
re.exec(s); // => ['l']
re.exec(s); // => ['o']
Note the g flag! This means that regex will match multiple occurencies instead of one!
EDIT
I suggest instead of using regex.exec(string) to use string.match(regex) if possible. This will yield an array of occurences and it is easy to inspect the array or to iterate through it.

javascript retrieve value from JSON object by matching key using Regex

I have the following javascript object literal (excerpt)
var foo = {"hello[35]":100,"goodbye[45]":42};
I have the following query:
var query = "hello"
I would like to call foo[query] to obtain the value 100, but there is a [35] for which I don't necessarily know the value of. I know for sure that I will get a unique match. Is there any way to input query is some kind of javascript regular expression? i.e.
Regex = /hello/
foo[Regex]
100
pardon the noob question...
What you have here:
var foo = {"hello[35]":100,"goodbye[45]":42};
is not JSON, which is a string representation of an object; what you have is an object literal, which creates an actual JavaScript object. As far as I know the only way to retrieve a value from an object by matching a property name with a regex is to enumerate the property names and test each one. The regex you'll need is something like:
/^hello(\[\d*\])?$/
...which will match against "hello" optionally followed by zero or more digits in square brackets. But you don't want to hard code "hello" given that you also (presumably) need the "goodbye" value, so use a function:
function getPropertyByRegex(obj,propName) {
var re = new RegExp("^" + propName + "(\\[\\d*\\])?$"),
key;
for (key in obj)
if (re.test(key))
return obj[key];
return null; // put your default "not found" return value here
}
var foo = {"hello[35]":100,"goodbye[45]":42};
alert(getPropertyByRegex(foo, "hello")); // 100
alert(getPropertyByRegex(foo, "goodbye")); // 42
alert(getPropertyByRegex(foo, "whatever")); // null (not found)
Demo: http://jsfiddle.net/asDQm/
Not sure if you can use regex without any plugins or so ...
This might help already ...
var foo = {"hello[35]":100,"goodbye[45]":42};
var query = "hello";
for(var key in foo){
if (key.indexOf(query) > -1)
document.write(foo[key]);
}
http://jsfiddle.net/3qqSr
I am noob here too but I have seen this page previously see it helps you with your question. It basically explains JSon path. Also see this question.
As your JSON is a string, you can use a regexp with this kind of statement:
var foo = '{"hello[35]":100,"goodbye[45]":42}';
var result = foo.match(/"hello\[\d*\]":\d*/g);
result = result[0].split(":")[1];
alert(result);
See it live on jsfiddle
Note that you could use a var instead of "hello" in your regexp.
var foo = {"hello[35]":100,"goodbye[45]":42};
foo = foo.replace(/\[\d+\]/g,'');
var obj = (new Function("return "+foo))();
obj.hello -> 100
obj.goodbye -> 42
var query = 'hello';
obj[query] -> 100
function getVal(s, q){
var r = s.match(new RegExp(q + "\\[\\d*\\]\":(\\d*)[\\,\\}]"));
return r?r.pop():false;
}
getVal(foo, "hello")

JavaScript validation: regex to validate numbers with comma

How do I use JavaScript regex to validate numbers like this?
1,000
1,000.00
1000.00
1000
I tried this (the string used should not match):
test('2342342342sdfsdfsdf');
function test(t)
{
alert(/\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d/.test(t));
}
but still gives me true.
If you want to test if the complete input string matches a pattern, then you should start your regex with ^ and end with $. Otherwise you are just testing if the input string contains a substring that matches the given pattern.
^ means "Start of the line"
$ means "End of the line"
In this case it means you have to rewrite you regex to:
/^(\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d)$/
If you would omit the extra parentheses, because otherwise the "|" would have lower precedence than the ^ and $, so input like "1,234.56abc" or "abc.12" would still be valid.
I'm not sure what you mean by validate. But this might work.
//console.log is used in firebug.
var isNumber = function( str ){
return !isNaN( str.toString().replace(/[,.]/g, '') );
}
console.log( isNumber( '1,000.00' ) === true );
console.log( isNumber( '10000' ) === true );
console.log( isNumber( '1,ooo.00' ) === false );
console.log( isNumber( 'ten' ) === false );
console.log( isNumber( '2342342342sdfsdfsdf') === false );
try this
var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));

Categories

Resources