regular expression to check only one decimal point - javascript

I have following regular expression to check only one decimal point for type number tag in html
^-?[0-9]*\\.?[0-9]*$
but this regular failed to check If I put decimal at the end e.g 12.12.
what further I have to add to check this

I think your regex can be easily fixed using a + instead of last * quantifier:
^-?[0-9]*\.?[0-9]+$
Tests:
const regex = /^-?[0-9]*\.?[0-9]+$/gm;
console.log('regex.test?')
console.log('12 = ' + regex.test('12'));
console.log('12. = ' + regex.test('12.'));
console.log('12.1 = ' + regex.test('12.1'));
console.log('12.12. = ' + regex.test('12.12.'));
console.log('-1 = ' + regex.test('-1'));
console.log('-1. = ' + regex.test('-1.'));
console.log('-1.2 = ' + regex.test('-1.2'));
console.log('-.12 = ' + regex.test('-.12'));
console.log('-. = ' + regex.test('-.'));
console.log('-. = ' + regex.test('-'));
console.log('. = ' + regex.test('.'));
Demo

Can you try the below : [1-9]\d*(\.\d+)?$

The simplest way to allow a possible . at the end is to have \.? just before the $. Also, the double \ looks wrong (unless you need it for escaping a \ in the context in which you are using it):
^-?[0-9]*\.?[0-9]*\.?$
But please recognize that your regex does not require any actual digits, so will match some non-numbers, like ., -. and (with my edit) -.. The above regex will also match an empty string!
You will want to either change your regex to require digits, or take into account somewhere else that they might not be there.

Related

How to replace HTML special character in javascript?

var Value="!##$'&\";
if (value.indexOf("'") > 0) {
value = value.replace(/'/g, "'");
}
All Text is replaced except last character "\".
How do i replace it with same.
I have new information about this solution from #MarcoS:
var value = "!##$'&\\";
value = value.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
I am not sure when it started, but as of today 2019/07/10, this code will not work in chrome, but it does work in firefox/safari. It will cause the lowercase 's' character to trip the regex and output as encoded s A coworker of mine found that this character \u017f, now in the unicode standard, and causes this code to act strangely:
http://www.fileformat.info/info/unicode/char/17f/index.htm
If you instead use the following, it should work in all browsers:
var value = "!##$'&\\";
value = value.replace(/[\u00A0-\u017e\u0180-\u9999]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
This is the currently 'accepted' code to convert all (or a range of them) possible unicode characters to their equivalent HTML entity:
var value = "!##$'&\\";
value = value.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
There is a syntax error, that once fixed will also replace the \ character:
You need an extra backslash because backslash is a special character and needs to be escaped.
var value= "!##$'&\\";

Check for existence of a keyword within a code string

I’m loading the contents of a JS file using FileReader and dumping the results into a textarea container. I then want to run some checks on the actual JS file.
I know there are probably tools out there for this already (or better ways), but this is for a closed-environment project.
After the textarea contains the content of the JS file as one large string, I need to loop the string and find all instances of parseInt() to check if they have been supplied with a radix.
I would provide code, but I have nothing working at this point. Any ideas?
The following snippet will search the string value of your <textarea> element for parseInt() and output the occurences, with radix where applicable:
var textareaValue = 'var func = function(){' +
'var i = parseInt(1,1);' +
'var j = parseInt(10, 10);' +
'var k = parseInt(3) + j;' +
'};';
occurences = textareaValue.match(/parseInt\(.+?(, ?\d+)?\)/g);
occurences.forEach(function(occurence){
var hasRadix = /, ?\d+\)$/.test(occurence);
document.body.innerHTML += '<p>"' + occurence + '" has ' +
(hasRadix ? 'a' : 'no') + ' radix' +
(hasRadix ? ' (' + occurence.match(/, ?(\d+)\)$/)[1] + ')' : '') +
'.</p>';
});
Note that this is no actual syntax interpretation, it’s merely text analysis. You will have to go from the result, which comprises all the occurences of parseInt() as strings. Also, JavaScript allows whitespace, comments, expressions and other witchcraft at the text passage in question. You might to have to check for anything.
The actual regex /parseInt\(.+?(, ?\d+)?\)/g will demand…
parseInt( at the beginning of the match
any characters (might need to be expanded to include brackets, etc. by :punct:)
as optional group, determining whether a radix is supplied or not:
a comma, an optional space (might need to respond to any number of whitespace using *)
at least one digit (might need to limit to {1,2}, because only 2 to 36 are valid)
a trailing closing bracket.
The following function should be able to tell the difference between usages of parseInt with radix versus its usages without radix by simplistic regex matching:
function have_radix(str){
parseIntRegex = /parseInt\(.+?\)/g;
parseIntRegexWithRadix = /parseInt\(.+?(,.+?\))/g;
indices = [];
while ( (result = parseIntRegex.exec(str)) ) {
indices.push(result.index);
}
count = indices.length;
indices = [];
while ( (result = parseIntRegexWithRadix.exec(str)) ) {
indices.push(result.index);
}
diff = count - indices.length;
return diff;
}

Javascript/Regex: Expression works in one environment and not another

I am trying to only allow alphanumeric entry or these characters:'()-_. (with the "." included)
Using regexpal.com I entered this regular expression: [^a-zA-Z0-9()\.'\-\_ ]
It is correctly identifying * and # as a match. What's baffling is that I have that same exact expression in my javascript on an .aspx page and it is not catching * or #. I have confirmed that is indeed entering that function and that the expression evaluates. Here is that code:
$(".validateText").keyup(function (e) {
var matchPattern = "[^a-zA-Z0-9()\.'\-\_ ]";
var regEx = new RegExp(matchPattern);
console.log("Regex: " + regEx + "\nValue of " + e.target.id + " is: " + e.target.value);
if (regEx.test(e.target.value)) {
console.log("Found invalid data.");//I don't get here with # or *
var failingChar = e.target.value.length - 1;
e.target.value = e.target.value.substring(0, failingChar);
}
});
Rather than using string literals to define regexes, use regex literals.
var regEx = /[^a-zA-Z0-9()\.'\-\_ ]/;
String literals interpret backslashes as escape characters, so they need to be escaped. Regex literals don't require this.
As per Bergi's suggestion, you wouldn't even need to escape all those characters.
/[^a-zA-Z0-9().'_ -]/
You could probably even use the general \w character.
/[^\w().' -]/
var matchPattern = "[^a-zA-Z0-9()\\.'\\-\\_ ]";
Would work.

Validating a string pattern in regex

I have the following string:
/xyz/10.2005/abc.d10.1/example
Here what I want to validate is, there should not be a space after "/xyz/".
Like It should not accept if the string is:
/xyz/ 10.2005/abc.d10.1/example
But it should accept if the string is:
10.2005/abc.d10.1/example
How can I modify the following regex to validate the above thing??
REGEX- "^\\S*((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?)"
Could someone help me??
This may be what you are looking for (it's a literal, you can convert it to a string if you really need to use the RegExp constructor):
var re = /^(\/\w+\/10|\s*10)\.\d+\/\w+\.\w\d+\.\d\/\w{7}/;
var s = '/xyz/10.2005/abc.d10.1/example';
var t = '/xyz/ 10.2005/abc.d10.1/example';
var u = ' 10.2005/abc.d10.1/example';
console.log(
's:' + re.test(s) + '\n' + // true
't:' + re.test(t) + '\n' + // false
'u:' + re.test(u) + '\n' // true
);
It does more than just validate the space after the /xyz/ part, I hope the rest is what you want.
actually you need to make it a lazy regex
just change it to this
^\\S*?((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?).*
see those ? and .* at the end
demo here : http://regex101.com/r/zJ7yX8
Here's a long RegEx:
/(?:\/[a-z]+\/)?\10\.\d{4}\/[a-z]{3}\.[a-z]\d{2}\.\d\/[a-z]{7}/i
// or the following if you don't want exact occurrences
/(?:\/[a-z]+\/)?10\.\d+\/[a-z]+\.[a-z]\d+\.\d\/[a-z]+/i
Matches:
/xyz/10.2005/abc.d10.1/example
10.2005/abc.d10.1/example
?: makes the group non-capturing.
The ? after the bracket-end symbolize it is optional.
Next is fairly simple RegEx.
For more explanation, here's a demo

Regex to get word started with # in javascript

I have a problem replace certain words started with #. I have the following code
var x="#google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
when I use the following code it works fine
var x="google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
it works fine
any suggestion how to make the first part of code working
ps. I use eval because x will be a user input.
The problem is that \b represents a boundary between a "word" character (letter, digit, or underscore) and a "non-word" character (anything else). # is a non-word character, so \b# means "a # that is preceded by a word character" — which is not at all what you want. If anything, you want something more like \B#; \B is a non-boundary, so \B# means "a # that is not preceded by a word character".
I'm guessing that you want your words to be separated by whitespace, instead of by a programming-language concept of what makes something a "word" character or a "non-word" character; for that, you could write:
var x = '#google'; // or 'google'
var pattern = new RegExp('(^|\\s)' + x);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
Edited to add: If x is really supposed to be a literal string, not a regex at all, then you should "quote" all of the special characters in it, with a backslash. You can do that by writing this:
var x = '#google'; // or 'google' or '$google' or whatever
var quotedX = x.replace(/[^\w\s]/g, '\\$&');
var pattern = new RegExp('(^|\\s)' + quotedX);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
Make you patter something like this:
/(#)?\w*/
If you want to make a Regular Expression, try this instead of eval:
var pattern = new RegExp(x);
Btw the line:
eval("var pattern = /" + '\\b' + x + '\\b');
will make an error because of no enclose pattern, should be :
eval("var pattern = /" + '\\b' + x + '\\b/');
How about
var x = "#google";
x.match(/^\#/);

Categories