jQuery Regular Expression Returns Unexpected Results - javascript

I'm trying to use the following code with jQuery to validate hex value strings but I get unexpected results:
var a = new RegExp("0x[a-fA-F0-9]+")
var result = a.test('0x1n')
In this case, result actually returns true. What am I missing here?

You need anchors to match the beginning and the end of the string. This will make the regular expression try to match against the entire string instead of just a part of the string:
var a = new RegExp("^0x[a-fA-F0-9]+$")
Otherwise your regular expression matches the 0x1 part and returns true.
On another note, the following would be a little better:
var re = /^0x[a-f0-9]+$/i;
The i flag makes it case insensitive so you don't have to specify a-f and A-F.

Your regex does match that string, because you don't have any anchors on it. If you change your regex to ^0x[a-fA-F0-9]+$, then the string 0x1n will not match.
Edit: To further explain why your string matches, your regular expression is actually trying to match a string that contains 0x followed by one or more characters in the [a-fA-F0-9] character class. The string 0x1n contains 0x followed by 1, which is in the [a-fA-F0-9] character class.
Adding anchors means that your string must start with 0x, then finish with one or more characters in the [a-fA-F0-9] character class. 0x1n would fail to match, since it ends in an n, which is not in that character class.

It returns true because you're not requiring the entire string to match that pattern. Try this:
var a = new RegExp("^0x[a-fA-F0-9]+$")

Related

reactStringReplace() inconsistent regex match

I'm trying to use react-string-replace to match all $Symbols within a string of text.
Here are a few example values we'd like to be matched (stock / crypto / forex pairs): $GPRO, $AMBA, $BTC/USD, $LTC/ETH
Here is our attempted regex
/\$\S+[^\s]*/g
when passing the string
$this works great $this/works great too.
through .match() - the proper symbols are returned in an array.
0: "$this"
1: "$this/works"
When using
reactStringReplace() - each match is returning
works great
Any ideas why
reactStringReplace()
seems to be handling this regex incorrectly?
Thanks ya'll!
Check the React String Replace documentation, it is written there:
reactStringReplace(string, match, func)
...
match
Type: regexp|string
The string or RegExp you would like to replace within string. Note that when using a RegExp you MUST include a matching group.
Why should you add a capturing group? See the replaceString function. There is var result = str.split(re); line that uses the pattern to actually split the contents you pass to the regex with your pattern thus tokenizing the whole input into parts that match and those that do not match your regex.
If you do not add a group to the regex passed as a String, the capturing parentheses will be added automatically around the whole pattern:
if (!isRegExp(re)) {
re = new RegExp('(' + escapeRegExp(re) + ')', 'gi');
}
If you pass your regex as a RegExp without capturing parentheses, the matches will be missing from the resulting array, hence, they will disappear.
So, use
/(\$\S+)/g
If you want to keep the $ chars in the output, or
/\$(\S+)/g
if you want to omit the dollars.

Regular expression for not allowing spaces in the input field

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

Javascript - Replace substring from string where the value is between specific characters

So I have this string, that represents a math expression:
(timezone*timelapse)-time
Each word represents an id from an input field, and currently i was merely replacing each word with a prototype js expression to be evaled later:
$('timezone').value,
$('timelapse').value
The problem is the last id. By the time i reach it, my expression is currently like this:
($('timezone').value*$('timelapse').value)-time
So when I search for the word time to replace it with $('time').value it will affect the first two values and messing the final expression.
My question here is: How can I replace the correct word here?
Since this a math expression the word should probably be between any math symbols like this:
(+-/* **word** +-/*)
[empty space] **word** +-/*)
(*-/* **word** [empty space]
Or not?
You can replace all with one replacement, then you don't have the double replacement problem:
exp = exp.replace(/([A-Za-z]+)/g, function(m){
return "$('" + m + "').value";
});
If it's a straight replacement without any logic, you can also use the caught value in a replacement string, as Cerbrus suggested:
exp = exp.replace(/([A-Za-z]+)/g, "$('$1').value");
Try this:
var newString = oldString.replace(/\btime\b/, "$('time').value")
\b is a word boundary, meaning the regex only matches time if it's a stand-alone word, not when it's directly followed or preceded by any word characters.

JavaScript regexp not matching

I am having a difficult time getting a seemingly simple Regexp. I am trying to grab the last occurrences of word characters between square brackets in a string. My code:
pattern = /\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
if (pattern.test(text)) {
alert(RegExp.lastMatch);
}
The above code is outputting "gemstones_attributes", when I want it to output "shape". Why is this regexp not working, or is there something wrong with my approach to getting the last match? I'm sure that I am making an obvious mistake - regular expressions have never been my string suit.
Edit:
There are cases in which the string will not terminate with a right-bracket.
You can greedily match as much as possible before your pattern which will result in your group matching only the last match:
pattern = /.*\[(\w+)\]/g;
var text = "item[gemstones_attributes][0][shape]";
var match = pattern.exec(text);
if (match != null) alert(match[1]);
RegExp.lastMatch gives the match of the last regular expression. It isn't the last match in the text.
Regular expressions parse left to right and are greedy. So your regexp matches the first '[' it sees and grabs the words between it. When you call lastMatch it gives you the last pattern matched. What you need is to match everything you can first .* and then your pattern.
i think your problem is in your regex not in your src line .lastMatch.
Your regex returns just the first match of your square brackets and not all matches. You can try to add some groups to your regular expression - and normally you should get all matches.
krikit
Use match() instead of test()
if (text.match(pattern))
test() checks for a match inside a string. This is successfull after the first occurence, so there is no need for further parsing.

Javascript: String replace problem

I've got a string which contains q="AWORD" and I want to replace q="AWORD" with q="THEWORD". However, I don't know what AWORD is.. is it possible to combine a string and a regex to allow me to replace the parameter without knowing it's value? This is what I've got thus far...
globalparam.replace('q="/+./"', 'q="AWORD"');
What you have is just a string, not a regular expression. I think this is what you want:
globalparam.replace(/q=".+?"/, 'q="THEWORD"');
I don't know how you got the idea why you have to "combine" a string and a regular expression, but a regex does not need to exist of wildcards only. A regex is like a pattern that can contain wildcards but otherwise will try to match the exact characters given.
The expression shown above works as follows:
q=": Match the characters q, = and ".
.+?": Match any character (.) up to (and including) the next ". There must be at least one character (+) and the match is non-greedy (?), meaning it tries to match as few characters as possible. Otherwise, if you used .+", it would match all characters up to the last quotation mark in the string.
Learn more about regular expressions.
Felix's answer will give you the solution, but if you actually want to construct a regular expression using a string you can do it this way:
var fullstring = 'q="AWORD"';
var sampleStrToFind = 'AWORD';
var mat = 'q="'+sampleStrToFind+'"';
var re = new RegExp(mat);
var newstr = fullstring.replace(re,'q="THEWORD"');
alert(newstr);
mat = the regex you are building, combining strings or whatever is needed.
re = RegExp constructor, if you wanted to do global, case sensitivity, etc do it here.
The last line is string.replace(RegExp,replacement);

Categories