I have a string and want to wrap non-numbers with double quotes (if they don't have them already). What is the best way to detect a non-number with a regex?
These are numbers: 123.43, 13827. These are non numbers: Hello, 2011-02-45, 20a, A23.
Here is the regex I currently have but does not handle the case where a non-number starts with a digit (so 2011-02-45 is not picked up).
str = str.replace(/(['"])?([a-zA-Z0-9_\-]+)(['"])?:/g, '"$2":');
str = str.replace(/:(['"])?([a-zA-Z_]+[a-zA-Z0-9_]*)(['"])?/g, ':"$2"');
How about this:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Taken from: Validate decimal numbers in JavaScript - IsNumeric()
I found the solution by reading another question. This is it:
str.replace(/(['"])?([a-zA-Z0-9_\-]*[a-zA-Z_\-]+[a-zA-Z0-9_\-]*)(['"])?/g, '"$2"');
The trick is to ensure there is a non-digit in the match.
you can do something like this, which is alot quicker than regexp!
str = +str||false;
str = 123.4 or, false when not a number
This is to typecast "str" into a real number or leave it as a string you can..
str = +str||str||false;
to take that to the next step, you can check your output:
if(typeof(str)=='string'){
//str is a string
}
Related
How can I replace a decimal in a number with a string? For example, if I have a number 12.12, how can I take the decimal in that number and replace it with a comma (,) so that the output would be 12,12?
I tried this, but my app crashes because of it:
let number = 12.12
number.replace(/./g, ',');
Thanks.
You cannot use replace on a number, but you can use it on a string.
Convert your number to a string, and then call replace.
Also, the period (.) character has special meaning in regular expressions. But you can just pass a plain string to replace.
const numberWithCommas = number.toString().replace('.', ',');
try this:
var stringnumber = stringnumber.ToString();
var endresult = stringnumber.replace(".",",");
You cannot change the value of a const in javascript.
I need to check a value if it is numeric and optionally contains commas.
I tried
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$/;
pattern.test(input);
but it always gave me false;
I don't want to use $.isNumeric as it does not check for commas.
Assuming you're using the comma as a thousands separator, the easiest way to do this is to just remove the commas when converting:
var num = +str.replace(/,/g, '');
if (!isNaN(num)) {
// It's a valid number
}
If your locale uses . as the thousands separator and , as a decimal point (as your regex seems to suggest), since JavaScript always uses them the other way around, we have more to change in the string first:
var num = +str.replace(/\./g, '').replace(/,/g, ".");
if (!isNaN(num)) {
// It's a valid number
}
I must process in different ways strings and string-numbers.
So I must test if a string is a string-number (not a valid number), using the locale convention.
My rude solution is:
var num = +str.replace(/\./g, '').replace(/,/g, '');
if (!isNaN(num))...
This works with USA, EUR locales. The control about 'valid number' is done after, car I wanna send detailed WARNING/ERROR messages to user.
Your sample var input is not matched by your regex because of the dot.
You could do:
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.?\d{3})*(,\d+)?$/;
// the dot is optional __^
pattern.test(input);
This regex will match:
123
1234
1.234
123,45
1234,567
1.234,56
1.234.567,89
I'm trying to write a regex to verify that an input is a pure, positive whole number (up to 10 digits, but I'm applying that logic elsewhere).
Right now, this is the regex that I'm working with (which I got from here):
^(([1-9]*)|(([1-9]*).([0-9]*)))$
In this function:
if (/^(([1-9]*)|(([1-9]*).([0-9]*)))$/.test($('#targetMe').val())) {
alert('we cool')
} else {
alert('we not')
}
However, I can't seem to get it to work, and I'm not sure if it's the regex or the function. I need to disallow %, . and ' as well. I only want numeric characters. Can anyone point me in the right direction?
You can do this way:
/^[0-9]{1,10}$/
Code:
var tempVal = $('#targetMe').val();
if (/^[0-9]{1,10}$/.test(+tempVal)) // OR if (/^[0-9]{1,10}$/.test(+tempVal) && tempVal.length<=10)
alert('we cool');
else
alert('we not');
Refer LIVE DEMO
var value = $('#targetMe').val(),
re = /^[1-9][0-9]{0,8}$/;
if (re.test(value)) {
// ok
}
Would you need a regular expression?
var value = +$('#targetMe').val();
if (value && value<9999999999) { /*etc.*/ }
var reg = /^[0-9]{1,10}$/;
var checking = reg.test($('#number').val());
if(checking){
return number;
}else{
return false;
}
That's the problem with blindly copying code. The regex you copied is for numbers including floating point numbers with an arbitrary number of digits - and it is buggy, because it wouldn't allow the digit 0 before the decimal point.
You want the following regex:
^[1-9][0-9]{0,9}$
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits.
#"(?<!\d)\d{10}(?!\d)"
check this site here you can learn JS Regular Expiration. How to create this?
https://www.regextester.com/99401
I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"
I want to replace the numbers in the string with _number.We have to fetch the numbers only that dont begin with a character and replace them with a underscore .
Requirement : I have a string, so while processing I want to replace constants with _Constant.
example string :"(a/(b1/8))*100"
output expected :"(a/(b1/_8))*_100"
Please suggest how to do this in asp.net code behind.
Thanks in advance.
You'll need a regular expression and the replace function:
var str = '(a/(b1/8))*100';
alert( str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2') );
So, what's going on?
The /'s mark the beginning and end of the regular expression (the tool best suited to this task).
[^a-zA-Z0-9] means "nothing which is a letter or a number".
[0-9] means "a digit".
Together, they mean, "something which is not a letter or a number followed by a digit".
The g at the end means "find all of them".
The () groups the regular expression into two parts $1 and $2
The '$1_$2' is the output format.
So, the expression translates to:
Find all cases where a digit follows a non-alphanumeric. Place a '_' between the digit and the non-alphanumeric. Return the result.
Edit
As an aside, when I read the question, I had thought that the JS function was the desired answer. If that is not the case, please read rkw's answer as that provides the C# version.
Edit 2
Bart brought up a good point that the above will fail in cases where the string starts with a number. Other languages can solve this with a negative lookbehind, but JavaScript cannot (it does not support negative lookbehinds). So, an alternate function must be used (a NaN test on substr( 0, 1 ) seems the easiest approach):
var str = '(a/(b1/8))*100';
var fin = str.replace(/([^a-zA-Z0-9])([0-9])/g, '$1_$2');
if( !isNaN( fin.substr( 0, 1 ) ) ) fin = "_" + fin;
alert( fin );
Same as cwallenpoole's, just in C# code behind
string str = '(a/(b1/8))*100';
str = Regex.Replace(str, '([^a-zA-Z])([0-9])', '$1_$2');
Updated:
string str = "(a/(b1/8))*100";
str = Regex.Replace(str, "([^a-zA-Z0-9]|^)([0-9])", "$1_$2");
Why not try regular expressions:
That is:
search for the regex: "[0-9]+" & replace with "_ + regex."
ie.
String RegExPattern = #"[0-9]+";
String str = "(a/(b1/8))*100";
Regex.Replace(str, RegExPattern, "_$1");
Source: http://msdn.microsoft.com/en-us/library/ms972966.aspx
Hope that helps ya some!