preg_match to Javascript function - javascript

$value = 077283331111333;
if( ! preg_match(/^[0-9]{1,20}+$/, $value))
{
echo $value . " is not a number that has between 1,20 digits";
}
I'm trying to turn this Php conditional statement into a Javascript one.
This is what I have, currently not working.
var value = 077283331111333;
var regex = '/^[0-9]{1,20}+$/';
var match = regex.test(value);
if ( ! match) {
console.log(value + 'is not a number that has between 1,20 digits');
}
And this is the error I'm getting.
Object /^[1,0]{1}+$//^[0-9]{1,20}+$/ has no method 'test'
Any ideas? Additionally this within a node.js environment.

That method is undefined because that's not a regex but a string.
You need to drop the quotes in order to create a RegExp object in javascript:
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;
Anyway I don't think that's a valid regex (because of the double slashes) you might wanna check for typos there...
A regex to check for a number between 1 and 20 digits is just:
var regex = /^\d{1,20}$/

try to remove single quotes from your regex
var value = 077283331111333;
var regex = /^[1,0]{1}+$//^[0-9]{1,20}+$/;
var match = regex.test(value);
if ( ! match) {
console.log(value + 'is not a number that has between 1,20 digits');
}

try remove the quotes from regex variable.

if ( /regex/.match( value ) ) {
//do stuff
}

That's one odd regexp... why don't you use
/^\d{1,20}$/.test(value)

Related

Javascript regex to replace "split"

I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)

String : Replace function with expression in Javascript

A string representing a currency is to be converted to a number.
For example:
Input : "125.632.454.454.403,51"
Output expected : 125632454454403.51
Currently I am trying:
Trial 1)
a = "125.632.454.454.403,51";
a.replace(/./, '');
Result = "25.632.454.454.403,51"
Trial 2)
a = "125.632.454.454.403,51";
a.replace(/./g, '');
Result = ""
But I expect the replace function to find all the occurrences of "." and replace by "".
Trial 3)
a = "125.632.454.454.403,51";
a.replace(/,/, '');
Result = "125.632.454.454.40351"
I would be glad if I find a fix for this.
You need to use \. instead of .. The dot (.) matches a single character, without caring what that character is. Also you can do it with single replace() with callback .
var str = "125.632.454.454.403,51";
str = str.replace(/\.|,/g, function(m) {
return m == '.' ? '' : '.'
});
document.write(str);
try:
var str = "125.632.454.454.403,51" ;
var result = str.replace(/\./g,'').replace(/\,/g,'.');
console.log(Number(result))
replace returns the changed string, it does not change it in-place!
You can find this out, by refering to the documentation.
Use
var Result = a.split('.').join("");
console.log(Result);
. has specific meaning in a regex. It matches any character. You need to escape the dot if you are actually looking for the character itself
var a = "125.632.454.454.403,51";
var result = a.replace(/\./g,"");
You can also do (parseFloat(a.replace(/[^0-9]+/g,""))/100)
And if you have to do this for multiple currencies, I would recommend looking into autonumeric.js. It handles all this for you.

How to remove strings with numbers and special characters using regular expression

Remove strings with numbers and special characters using regular expression.Here is my code
var string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
var numbers = string.match(/(\d+)/gi);
alert(numbers.join(','));
here output is : 0,1,1,2,2,3,3,4
But i want the following output 1,2,3,4
Can any one please help me.
Thanks,
Seemd what you want is [\d+], use exec like this,
var myRe = /\[(\d+)\]/gi;
var myArray, numbers = [];
while ((myArray = myRe.exec(string)) !== null) {
numbers.push(myArray[1]);
}
http://jsfiddle.net/xE265/
You can do:
string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
repl = string.replace(/.*?\[(\d+)\][^\[]*/g, function($0, $1) { return $1 });
//=> "1234"
I guess the simplest solution in this case would be:
\[(\d+)\]
simply saying that you only want the digits enclosed by brackets.
Regards

How to insert the parentheses and values if missing string?

Here i have group of string with comma, like "stack,flow(2),over(4),temp(0)" if just string without open and close parentheses value, i need to insert the with (1). stack(1).
Expected scenario :
1.insert (1) missing open & close parentheses
2.within parentheses should be >0 numeric values.
3.within parentheses if any alpha character , show error message.
As i need to validate that with in parentheses value should be numberic. I have tried the some scenrio, but i need help to insert (1).
function testCases(str){
return (
str.match(new RegExp("\\([^,]+\\)","g")).length == str.split(",").length
);
}
Here is jsfiddle
If I correctly understand you want to insert (1) before the comma if there's no parenthesized group, then you can do this :
var str = "stack,flow(2),over(4),temp(0)";
str = str.replace(/([^)]),/g, "$1(1),");
Result : "stack(1),flow(2),over(4),temp(0)"
If you also want to ensure the group contains a strictly positive integer, you may do
var str = "stack,flow(2),flow(k),over(4),neg(-3),temp(0)";
str = str.split(',').map(function(s){
return s.replace(/(\((.*?)\))?$/, function(s,d,e) {
return '('+ (e>0?e:1)+')'
})
}).join(',');
Result : "stack(1),flow(2),flow(1),over(4),neg(1),temp(1)"
well, my solution is a little complicated, but more relatable, e.g. it works for:
stacka(z),flow(2),over(4),temp(0),ccc
Here the code:
function convert(str) {
//ends with (num)
var regexObj = /\(\d+\)$/;
return str.split(',').map(function(p) {
return p + (regexObj.test(p) ? '' : '(1)');
}).join(',');
}
http://jsfiddle.net/rooseve/pU2Q7/

startswith in javascript error

I'm using startswith reg exp in Javascript
if ((words).match("^" + string))
but if I enter the characters like , ] [ \ /, Javascript throws an exception.
Any idea?
If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()
A better solution would be to use substr() like this:
if( str === words.substr( 0, str.length ) ) {
// match
}
or a solution using indexOf is a (which looks a bit cleaner):
if( 0 === words.indexOf( str ) ) {
// match
}
next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:
String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}
When added to the prototype you can use it like this:
words.startsWith( "word" );
One could also use indexOf to determine if the string begins with a fixed value:
str.indexOf(prefix) === 0
If you want to check if a string starts with a fixed value, you could also use substr:
words.substr(0, string.length) === string
If you really want to use regex you have to escape special characters in your string. PHP has a function for it but I don't know any for JavaScript. Try using following function that I found from [Snipplr][1]
function escapeRegEx(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
and use as
var mystring="Some text";
mystring=escapeRegEx(mystring);
If you only need to find strings starting with another string try following
String.prototype.startsWith=function(string) {
return this.indexOf(string) === 0;
}
and use as
var mystring="Some text";
alert(mystring.startsWith("Some"));

Categories

Resources