How to remove characters when input not matches regex in JS - javascript

<input id="myInput" onblur="myFunction()">
<script>
function myFunction() {
var value= document.getElementById('myInput').value;
var regexCharacter = /[0-9|,]+/g;
strFirst = value.replace(regexCharacter, '')
document.getElementById('myInput').value = strFirst
}
</script>
I want to replace '' when the input does not match the regex's.
My regex just allow input number and comma.
My function is replace when input matching, i want to replace when it's not matching.
E.g a12,b2a => 12,2
can anyone help me, thanks.

Use /[^0-9|,]+/g as your regex. The ^ mark is used to match any character that's not in range.
Pro tip: You dont have to memorize all these tokens, just use a tool like https://regex101.com/

First of all, your function is not called to check the value with reqex.
then yout reqex replace "" when is number not charactors
<input type="text" id="myInput">
<script>
myInput.addEventListener("input", function (e) {
var value= document.getElementById('myInput').value;
strFirst = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
document.getElementById('myInput').value = strFirst
});
</script>
in this code you can write number whith dot
whith this reqex
value.replace(/[^0-9.]/g, '').replace(/(..?)../g

I think you should edit your regex to match letters instead of numbers. Like this: /[a-zA-Z|]+/g

Related

Regex check always return null\false\-1

I have a simple calculator on ASP.NET MVC5, front side is on HTML\CSS\Javascript.
In event handlers for buttons I concatenate all values into a string and want to check if it satisfies the regex. But, for example, if I put following values into my calculator: '99*66-', the code below returns null every time.
Here regex works okay: https://regex101.com/r/AxMvPe/1
Whole code: https://jsfiddle.net/0g79hkbc/
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear https://regex101.com/
$('.button').on('click', function () {
var buttonText = this.innerHTML;
var inputedText = inputElement.innerHTML + buttonText;
console.log(inputedText.match(regEx));
});
I have tried following options, but they didn't help:
to replace regex expression on Regex object
to use .test() instead of .match() (got false)
to use .search() instead of .match() (got -1)
I also tried to manually entered '99*66-' and then compare inputedText with javascript string '99*66-', it also returns false. Why?
Looks good to me, except that it will not match when there is for example 99*. You will need a repeating set of regex like: https://regex101.com/r/AxMvPe/2
Added floats to it :)
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear
inputElement = $('#input');
$('.button').on('click', function () {
var buttonText = $(this).val();
var inputedText = inputElement.val() + buttonText;
console.log(inputedText.match(regEx));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='input' type='text' value='99*66' />
<input class='button' type='button' value='-'/>

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format. This should occure .on("input") meaning as the user types it should secure the right input format.
A wrong char should be replaced with a blank.
Format Example: 1.000 1.281 21212.000 21212.810Nothing like this:1.02.12 or 1919,201,00 Only a dot between the two Number blocks.
This is what i have so far:
Regex 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
Regex 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
Regex 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.
Here is the FIDDLE
Should Work in IE11
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
try this one,
^[0-9]*(\.|,)?[0-9]*$
this take below cases:
1111,
.0000
123,12
12.12
12345
but if you want only
111,11
11.11
12345
so please use this
^[0-9]+(\.|,)?[0-9]+$
to force use dot/comma please use this
^[0-9]+(\.|,)[0-9]+$
add this code
$("#testId").keyup(function(){
var vals = $("#testId").val();
if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
$("#testId").val(vals);
else
vals = vals.replace(/.$/,"");
$("#testId").val(vals);
});
and change input type to
type="text"

Javascript strip after X characters prior to form submit

UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).

Removing last word from an input value

I've been trying to remove the last word of an input value using the following code:
$('#buttonid').on('click',function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0,textVal.length - 1));
});
This code removes only one letter from the word. I know I can delete the whole word by specifying the number of its letter in textVal.length - 1. However, the word is not static, so I want to use something that removes any last word in the input value.
Edit, Note: Words are separated by dots, not spaces.
Any suggestions?
You can use lastIndexOf method to find a position of the last dot separating last word:
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf('.')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonid">Remove</button>
<input type="text" id="inputid">
You can also make your code a little cleaner if you don't reselect the same element again but use a function in the val method:
$('#buttonid').on('click', function () {
$('#inputid').val(function() {
return this.value.substring(0, this.value.lastIndexOf('.'));
});
});
Bonus point. If you want you can use very simple regular expression (although it might be overkill here, but regexp is more reliable then '.' in lastIndexOf) to remove everything after the last word boundary, for example:
$('#inputid').val(function() {
return this.value.replace(/\b.\w*$/, '');
});
Use lastIndexOf(' ') instead of length - 1. The former will take the last index of a space (which signifies the last word, barring any edge cases you may have) and use it as the end point for your substring.
The latter is supposed to only give you the index of the last letter, since calling textVal.length would result in the number of actual characters in the string, not words.
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf(' '));
Another option would be to transform the text to an array, and pop() it, to remove the last element. Then, rejoining it using space as a separator.
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val().split(' ');
textVal.pop();
$('#inputid').val(textVal.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputid"></textarea><br>
<button id="buttonid">Remove Word</button>
You can use the lastIndexOf method to get the last index of occurring peroid. Here's the code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#buttonid").on('click',function ()
{
//get the input's value
var textVal = $('#inputid').val();
var lastIndex = textVal.lastIndexOf(".");
$('#inputid').val(textVal.substring(0,lastIndex));
});
});
</script>
</head>
<body>
<input type="button" id="buttonid" value="Go">
</input>
<input type="text" id="inputid" value="Anything.could.be">
</input>
</body>
</html>

regex is not filtering text

<script type="text/javascript">
function clean(e){
var textfield = document.getElementById(e);
var regex = /[^a-z 0-9]/gi;
textfield.value = textfield.value.replace(regex, "");
}
</script>
<textarea id="ta" name="ta" onkeyup="clean('ta')" onkeydown="clean('ta')"></textarea>
as you can see that my code filter all the alphabet character and i expected to do this in real time but this code is not working. Please help me to sort out this problem.
Fiddle represtation
You can remove all alphabets (A-Za-z) with this:
DEMO
function clean(e) {
var textfield = document.getElementById(e);
var regex = /[a-z]/gi; // all alphabet characters ignorecase
textfield.value = textfield.value.replace(regex, "");
}
And you need to keep your JavaScript code in <script> tag, in the html, because when it by the time it reaches onclick="clean('ta')", it hasn't yet reached the declaration of the function clean and hence throws a ReferenceError (which you see in the console (F12))
Check this demo jsFiddle
What can i do?
Modify your existing regular expression to update this /[a-zA-Z]/gi to ignore both uppercase and lowercase alphabetically character.
Here I can validate your regular expression
HTML
<textarea id="ta" name="ta" onkeyup="clean('ta')" onkeydown="clean('ta')"></textarea>
JavaScript
function clean(e) {
var textfield = document.getElementById(e);
var regex = /[a-zA-Z]/gi;
textfield.value = textfield.value.replace(regex, "");
}
Hope this help you!

Categories