Regex to globally accept back space in javascript - javascript

I've got this regex that I'm using to restrict currency fields and it works great because I can simply replace the . with a , and I can easily localize it on the fly. My only issues is I can't seem to delete the last remaining character using this regex and I would like to be able to do that. is there a way to modify this regex to allow that?
^[+-]?([\b0-9])+[.]?([0-9])+$
EDIT: The regex above is being passed as a string through props in react to an input field. The input field is then checking this method before updating its value
matchRegex = (reg, val) => {
const regex = new RegExp(reg, "gm");
if (regex.test(val)) {
return true;
}
return false;
};

I was actually able to figure this one out. Since I'm intercepting the keystrokes, I actually don't need to worry about the whole string and can focus on one input character at a time so the following was able to meet my needs:
^([\b^0-9.-])*$

Related

How do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

Javascript Regex - Match string shorter than expression?

let productIdPattern = /[0-9]{3}[A-Z]{3}[0-9]{3}/
let userInput = '123A'
if (userInput.match(productIdPattern)) {
alert("'123A' is ok, go ahead typing!")
}
Given is the above JavaScript pseudo code.
A User is typing a Product-ID. For every keystroke I want to check if the input will match the Product-ID pattern. If not, the keystroke will be ignored. So the input must follow the pattern.
For example:
Current input is "123", User presses "4" which is not valid and will be ignored.
Current input is "123", User presses "X" which is valid and will be appended to the input.
Is there a way to achieve this without making many different or complex patterns for each input length? I need a way to tell the "String.match()" function to ignore the rest of the pattern, if the string is shorter than the pattern.
We can create an input filter that only allows entering the desired pattern; everything else is immediately dropped. This is achieved using an in-place replacement pattern:
<input type="text" formControlName="productIdInputC"
onkeyup="this.value = this.value.replace(/^([0-9]{3}[A-Z]{3}[0-9]{1,3}|[0-9]{3}[A-Z]{1,3}|[0-9]{1,3})?.*$/, '$1')">
Though, you should still have server-side validation.
Try this pattern instead:
/^(?:\d{1,3}|\d{3}[A-Z]{1,3}|\d{3}[A-Z]{3}\d{1,3})$/
You can see a visualization of how this works here.

How to check if firstname's and lastname's first characters are uppercase?

I have an input filed where users will enter their first and last name.
For example: (John Smith)
How can I check if the first character of first name (J) and first character of last name (S) is upper case? I want to return true if it matches and false if it doesn't match.
I have been finding solutions that say to try the RegExp ^[A-Z][a-z]*(-|\s)[A-Z][a-z]*$, but I don't know how to use it.
Thanks :)
There should be a few layers that you should implement.
The first is in your markup, set your input's pattern attribute equal to the following RegEx:
^[A-Z].* [A-Z].*$
The second is in your styling, style the input to include the following:
[selector] {text-transform: capitalize;}
The third is in your JavaScript, change the String from the input to a proper-cased equivalent using the following function that will allow you to convert the input's value in your form's submit event (courtesy of Tuan):
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Finally, the fourth would be in your back-end code, you would want to re-validate that the input matches the format there too. But since you didn't specify the back-end language, I cannot help you there.
Doing these four things accomplishes a few things. For the average user using your form, they'd input the desired format via the CSS styling. For the malicious user trying to bypass your desired behavior, the newb would just try to remove the pattern attribute only to get caught by the JavaScript. The user with a little more brains would remove the JavaScript only to get caught by the back-end code.
There is a good and simply answer here
function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Use a simple css to capitalize your input:
input {
text-transform: capitalize;
}
<input type="text" name="textfield">

Allow only digit, comma or dot in the user input in JS

I have a user input where only a certain set of characters is allowed. That is, user should be able to enter only a number, possibly with floating point. User may use either comma or dot as a separator.
I've decided to implement this using JS replace function. My approach is to replace everything that doesn't match the set with empty string.
I've sorted out the regex to match the set pretty quickly, here it is:
^\d+[,.]{0,1}\d+$
I know it's probably not ideal, but it's quite okay since there is a server-side validation anyway.
However, no matter how hard I tried, I was not able to figure out how to replace anything that doesn't match this regex with empty string.
Here's how I use replace:
var cleanInputOut = function (element) {
element.value = element.value.replace(/<RegEx goes here>/g, '')
}
I am probably doing it wrong. I would be okay even with quite simple functionality - simply replace any non-digit, not comma and not dot with empty string. I've tried negative lookahead in regex but unfortunately I was not able to make it work as I want to.
It looks like I figured it out using
/[^\d,.]/g
So the function is
var cleanInputOut = function (element) {
element.value = element.value.replace(/[^\d,.]/g, '')
}
I don't really get why the ^ character is used both to mark a negated set and the beginning of the line, but it appears to be working.
I tried this regex before and it behaved quite strangely from time to time but I am not sure the issue was with the regex itself. Anyway, any advices as to the approach or regex are welcome.

regex value check not working

Here is the page
If you select one of the 3 modems, it will open up the form below.
On the Billing > Address Line 1 field (left col), I'm trying to check for a PO Box entry and display a hidden message above the field. We're trying to discourage PO Box, but it should still allow submit, so I'm handling this separately from the jq val plugin on the form.
It's just not working, no matter what I try. The bind on the input is working, since it's logging properly, must be an issue with the regex, but I can't pinpoint it.
Here is the current js
var pobox = new RegExp('[PO.]*\\s?B(ox)?.*\\d+', 'i');
$("#bill_address1").bind("change paste keyup", function(){
if ($(this).val().match(pobox)) {
$('#pobox-warning').fadeIn(50);
console.log('box');
}
else {
$('#pobox-warning').fadeOut(50);
console.log('no box');
}
});
Any help would be appreciated - thanks!
It seems to me that a simple regex pattern like
/PO *Box/gi
would work best. Ignore case. Match the letters PO and any number of spaces followed by the word Box.
Edit:
Or to match the entire PO Box line with or without periods:
/P\.?O\.? *Box *\d*/gi
The initial part of your regular expression matches either a single "P", an "O", or a ".". You probably want something more like:
var pobox = /(P\.?O\.?)?\s*B(ox)?.*\d+/i;
It's much easier to use the native regular expression syntax in JavaScript when possible, as it appears to be in this case.
got it working with
var pattern = /^[P|p](OST|ost).*\s*[O|o|0](ffice|FFICE).*\s*[B|b][O|o|0][X|x]\s*(\d.)*/gi;
appreciate everyone's input

Categories

Resources