I have a regex which allows only to enter integers and floats in a text box.
Regex Code:-
("^[0-9]*(?:[.][0-9]*|)$");
But it gives an error when the user enters whitespace at the beginning and end of the entered values. I want the user to allow spaces at the beginning and at the end as optional, so I changed the regex as below but it didn't work.
Note: Spaces may be spaces or tabs.
Test Case: User might enter:
"10","10.23"," 10","10 "," 10.23","10.23 "
Any number of spaces are allowed.
("^(?:\s)*[0-9]*(?:[.][0-9]*|)$")
I am newbie with regex, so any help will be highly appreciated.
Thank you.
Try this:
/^\s*[0-9]*(?:[.][0-9]*|)\s*$/;
You don't have to wrap a single entity in a group to repeat it, and I have added a second zero-or-more-spaces at the end which is what you are missing to make it work.
Note: You have not posted the code you use to create the RegExp object, but if it is new RegExp(string), remember to escape your backslashes (by doubling them):
var r = new RegExp("^\\s*[0-9]*(?:[.][0-9]*|)\\s*$");
Also, as #Blender suggests, this can be simplified to:
/^\s*[0-9]*(?:\.[0-9]*)?\s*$/;
Or, using \d instead of [0-9]:
/^\s*\d*(?:\.\d*)?\s*$/;
You don't necessarily need a Regular Expression: !isNaN(Number(textboxvalue.trim())) would be sufficient.
Otherwise, try /^\s{0,}\d+\.{0,1}\d+\s{0,}$/. Test:
var testvalues = ["10","10.23"," 10","10 "," 10.23","10.23 ","10.24.25"];
for (var i=0;i<testvalues.length;i+=1){
console.log(/^\s{0,}\d+\.{0,1}\d+\s{0,}$/.test(testvalues[i]));
}
//=> 6 x true, 1 x false
Related
I have a structure of string, I need a regular expression that only picks up the numbers from the structure, and also the expression should report if the structure deviates from the mentioned rule (suppose if I missed any comma or full stop or braces etc)
The structure is - {'telugu':['69492','69493','69494'],'kannada':['72224']}
The regular expression I've tried is /\[(.*?)\]/g;
The above expression is working fine for picking only numbers from the given input, but it's not reporting for the missing of any comma, fullstop or braces etc.
var contentids = {'telugu':['69492','69493','69494'],'kannada':['72224']};
var pattern = /\[(.*?)\]/g;
while ((match = pattern.exec(contentids)) != null) {
var arrayContentids2 = new Array();
arrayContentids2 = match[1].split(",");
}
I am fetching only the numbers from the given input,but I need a validation of missing commas, fullstop, braces etc from the input.
To get all the numbers you can use a RegEx like this /\'(\d+)\'|\"(\d+)\"/g. The second part is only for numbers inside " instead of ', so you can remove this if you want.
To check the balance of braces i would use a simple counting loop and move through the input. I don't think that RegEx are the right tool for this job.
To search missing commas you could use the RegEx /([\'\"]\s*[\'\"])/g and /([\[\(\{]\d+)/g to find the tow errors in
{'telugu':['69492','69493','69494'],'kannada':[72224''72224']}
Hope this will help you
I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);
A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?
Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"
I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");
I have not had to do something like this in the past and am wondering if it is indeed possible. I am allowing multiple code numbers to be added in an so long as they are delimited by commas. What I am wanting to do is upon the user clicking on the "okay" button that a showing the numbers entered will show them one on top of each other with a "delete" button next to them. That part is easy...the hard part is getting the comma stripped out and the new line placed in its stead.
Are there any examples or samples that anyone can point me too?
You'd use String#replace with a regular expression using the g flag ("global") for the "search" part, and a replacement string of your choosing (from your question, I'm not sure whether you want <br> — e.g., an HTML line break — or \n which really is a newline [but remember newlines are treated like spaces in HTML]). E.g.:
var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/,/g, '<br>'); // Or \n, depending on your needs
Or if you want to allow for spaces, you'd put optional spaces either side of the comma in the regex:
var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/ *, */g, '<br>'); // Or \n, depending on your needs
To replace all occurrences of a string you need to use a regexp with the g (global) modifier:
var numlist = "1,4,6,7,3,34,34,634,34";
var numlistNewLine = numlist.replace(/,/g, '\n');
Alternatively, use .split() and .join()
var newList = numList.split(',').join('\n');
var numlist = "1,4,6,7,3,34,34,634,34";
var numlistNewLine = numlist.replace(',','\n');
No jQuery needed. String has a nice replace() function for you.
I have the following code:
var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01
This works awesomely just how I want it to work. I just want a tiny addition, which is something like:
var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01
However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.
You can do it with a regular expression:
x = x.replace(/,([^,]*)$/, ".$1");
That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.
Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:
x = x.replace(/\./g, '');
When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:
x.replace(/something/, "something else");
has no effect on the value of "x".
You can use a regexp. You want to replace the last ',', so the basic idea is to replace the ',' for which there's no ',' after.
x.replace(/,([^,]*)$/, ".$1");
Will return what you want :-).
You could do it using the lastIndexOf() function to find the last occurrence of the , and replace it.
The alternative is to use a regular expression with the end of line marker:
myOldString.replace(/,([^,]*)$/, ".$1");
You can use lastIndexOf to find the last occurence of ,. Then you can use slice to put the part before and after the , together with a . inbetween.
You don't need to worry about whether or not it's the last ".", because there is only one. JavaScript doesn't store numbers internally with comma or dot-delimited sets.