Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in
/^[^\.].*[^\.]$/;
But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."
How about
/^(?!\.)[^\.]*\.?[^\.]*(?!\.).$/
The correct regex for
my requirement is that I can have at most one dot ('.') in the string
and that can't be at the start and end
is
/^([^\.]|([^\.]*.?[^\.]))$/
/^([^\.]|([^\.].*[^\.]))$/ or /^[^\.].*[^\.]$/ accepts String
containing more than 1 dot . Hence it will also accept X..X too.
Please check working snippet also
validateString("XX.X");
validateString("X.X");
validateString("X...X");
validateString("X");
validateString("X.X.X");
validateString(".XX");
validateString("XX.");
function validateString(str){
console.log(/^([^\.]|([^\.]*.?[^\.]))$/.test(str));
}
With your current regex, you are targeting a string that should be at least 2 characters long, as both [^\.] parts are a mandatory character.
Your regex should include an extra check in case there is just one character, which you can do like this:
^([^\.]|([^\.]+\.?[^\.]+))$
Related
I am trying to edit a DateTime string in typescript file.
The string in question is 02T13:18:43.000Z.
I want to trim the first three characters including the letter T from the beginning of a string AND also all 5 characters from the end of the string, that is Z000., including the dot character. Essentialy I want the result to look like this: 13:18:43.
From what I found the following pattern (^(.*?)T) can accomplish only the first part of the trim I require, that leaves the initial result like this: 13:18:43.000Z.
What kind of Regex pattern must I use to include the second part of the trim I have mentioned? I have tried to include the following block in the same pattern (Z000.)$ but of course it failed.
Thanks.
Any help would be appreciated.
There is no need to use regular expression in order to achieve that. You can simply use:
let value = '02T13:18:43.000Z';
let newValue = value.slice(3, -5);
console.log(newValue);
it will return 13:18:43, assumming that your string will always have the same pattern. According to the documentation slice method will substring from beginIndex to endIndex. endIndex is optional.
as I see you only need regex solution so does this pattern work?
(\d{2}:)+\d{2} or simply \d{2}:\d{2}:\d{2}
it searches much times for digit-digit-doubleDot combos and digit-digit-doubleDot at the end
the only disadvange is that it doesn't check whether say there are no minutes>59 and etc.
The main reason why I didn't include checking just because I kept in mind that you get your dates from sources where data that are stored are already valid, ex. database.
Solution
This should suffice to remove both the prefix from beginning to T and postfix from . to end:
/^.*T|\..*$/g
console.log(new Date().toISOString().replace(/^.*T|\..*$/g, ''))
See the visualization on debuggex
Explanation
The section ^.*T removes all characters up to and including the last encountered T in the string.
The section \..*$ removes all characters from the first encountered . to the end of the string.
The | in between coupled with the global g flag allows the regular expression to match both sections in the string, allowing .replace(..., '') to trim both simultaneously.
Suppose the following data is entered by user in a text area
test\$ing
I need to extract and modify the data. Problem is that I am not able to distinguish between '$' and '\$'
I have made the following attempts.
indexOf('\\') gives -1
indexOf('\$') gives 4
indexOf('$') gives 4
charAt(4) gives $
I understand that java script treat '\$' as a single character. But how to distinguish whether the character is '$' or '\$'
I have gone through this post and the accepted solution suggests to change the original text by escape backslashes. Is this the only possible way? Even if this is the case, how to escape the backslashes in the original text?
Please help
\ is an escape character, which means that in order to get a literal version of that character you have to write two of them in a row. Thus, your string should be written as 'test\\$ing' in JavaScript source. (However, users don't need to escape this character when they are typing in the context of a <textarea>.) To find a blackslash followed by $ inside your string you would write:
string.indexOf('\\$') //=> 4
Demo Snippet:
var string = 'test\\$ing'
console.log(string.indexOf('\\')) //=> 4
console.log(string.indexOf('\\$')) //=> 4
console.log(string.indexOf('$')) //=> 5
console.log(string.charAt(4)) //=> '\'
If you work with a string 'test\$ing' then you can't detect '\' because it is removed.
If user types \$ inside textarea.value, then indexOf should work.
Please provide more code.
I want few validations like (for my url):
cars : valid
cars/ : valid
(Any number of '/' after cars are valid)
cars- : invalid
cars* : invalid
carsp : invalid
(Any other character after cars except '/' is invalid)
**cars/new: valid
cars/old: valid
(Once we get '/' we can have anything).**
What should be regex for this:
I tried with:
cars[/]*[^-]
Its not working.
^cars(\/.*)?$
^...$ String should start with, and end with (Or simply, the string should only contain).
cars cars
(...)? and possibly
\/.* a forward slash followed by any character.
It looks like you want "cars" followed by either
nothing
or anything starting by at least one /
So this would be
cars(\/.*)?
But the real problem here is determining what you really need. Some context might help.
Use a positive look-ahead assertion:
/^cars(?=\/).*/
If there is a slash right after 'cars' word than it considers the rest part of the string
Hope you all are doing good,
Here is my problem ,I wanted to split a string writing some code like
var searchingWords='Hi # All "SO Members"';
var searchTextList=searchingWords.match(/\w+|"[^"]+"/g);
what it does is it returns an array which is separated by blank space , double quotes so I get the value of array like
["Hi","All","\"SO Members\""] but special characters '#' is missing ( characters could be &,* etc), so I need required regular exp which will be pass to match function or is there other way to do it in javascript?
Please check the sample here
Thanks.
Been trying to come up with a regex in JS that could split user input like :
"Hi{user,10,default} {foo,10,bar} Hello"
into:
["Hi","{user,10,default} ","{foo,10,bar} ","Hello"]
So far i achieved to split these strings with ({.+?,(?:.+?){2}})|([\w\d\s]+) but the second capturing group is too exclusive, as I want every character to be matched in this group. Tried (.+?) but of course it fails...
Ideas fellow regex gurus?
Here's the regex I came up with:
(:?[^\{])+|(:?\{.+?\})
Like the one above, it includes that space as a match.
Use this:
"Hi{user,10,default} {foo,10,bar} Hello".split(/(\{.*?\})/)
And you will get this
["Hi", "{user,10,default}", " ", "{foo,10,bar}", " Hello"]
Note: {.*?}. The question mark here ('?') stops at fist match of '}'.
Beeing no JavaScript expert, I would suggest the following:
get all positive matches using ({[^},]*,[^},]*,[^},]*?})
remove all positive matches from the original string
split up the remaining string
Allthough, this might get tricky if you need the resulting values in order.