Regex one or two digit nubers sequences in input.val() [duplicate] - javascript

I have a text area and a user can input US zip codes in it separated by a comma or (comma and space).
It could be like
12345,45678, 89654
The following regex is working and is removing not allowed characters:
$object.val($object.val().replace(/[^\d\, ]/g, ''));
I would like to enhance it, so that
i always should have 5 digits in the beginning
after 5 digits, there should be a comma or comma and space
comma or (comma and space) should not be at the very end of the string. It must be 5 digit number at the end.
This needs to tackle the copy paste as well. The user may copy paste invalid length for the zip code.
Thanks

Use this regex:
^\d{5}(, ?\d{5})*$
It specifies 5 digits at the beginning: ^\d{5}
and any number of other comma, space, and 5 digit combinations: (, ?\d{5})*

You can use:
var s='12345,45678, 12345';
var m = s.match(/^(?:\d{5},\s?)*\d{5}$/);

<html>
<head>
<title></title>
<script type="text/javascript">
function Validate(txt) {
txt.value = txt.value.replace(/[^, 0-9]+/g, '');
}
</script>
</head>
<body>
<form>
<input type = "text" id ="txt" onkeyup = "Validate(this)" />
</form>
</body>
</html>

Related

How to enter whitespace only once after 4 characters in a string?

Hey I have a input where the user enters his social security number. To make the input more readable I want to insert a whitespace after the first 4 characters of the string. The social security number itself is 10 numbers long. So the result should looke like: 1234 567890. I only found solutions where a whitespace every 4 characters is inserted but no example which is similar to this. Has someone an idea how to solve this?
<input type="text" maxlength="10" #keyup="insertWhitespace()"/>
You can do this with the use of Regular Expression + HTML DOM Element addEventListener().
Reference Website For "Regular Expression": https://regexr.com/
With the help of a regular expression is a sequence of characters that specifies a search pattern in text or strings.
document.getElementById('example').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim();
});
<input id="example" maxlength="11" name="example" />
I think you should make your max length to 11 because white space also counts and try it with the following code
const ssn = document.querySelector("selector");
ssn.addEventListener("keyup",(e) => {
if(e.target.value.length === 4){
ssn.value += " "
}
})
Here is the solution (Javascript) to your problem:
The code below reads the input value and remove alphabets and then replaces the digit value with the appropriate space character only once as expected after 4 digits.
function insertWhitespace() {
document.getElementById('myElement').value = document.getElementById('myElement').value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim()
}
<input id="myElement" maxlength="11" onkeyup="insertWhitespace()" />

How can Javascript's regular expressions filter strings with multiple rules at the same time?

I need to process a piece of text into an array of words.
Delimiters between words are newlines, spaces, and various punctuation marks, and .
The code I wrote was able to handle other cases, but not the case.
Notice:I need to handle all cases within the same regex and cannot replace with spaces.
This code doesn't go wrong, it just runs in chrome and the result is not the expected value.
In the generated word array, "break up test the words" is a value(wrong), I need it to be 5: [break,up,test,the,words](right)
my code:
<!DOCTYPE html><html><head>
<script>
window.onload = function(){
var text = document.getElementById('text').textContent
// of below regex doesn't work
var word_array = text.split(/[ \t\n\r.?,"';:!(){}<>\/]| /)
console.log(text)
console.log(word_array)
}
</script>
</head><body>
<div id="text">this is text,break up test the words!ok</div>
</body></html>
The issue is that the regex sees &nbsp as those exact characters. You want to use '\xa0' instead.

Js, How to ignore symbols that contribute text length in textbox?

My goal is to count text that are not symbols in textbox. For example, if user type in email_ex_3/2#mail.com the original length of the text is 21 but my goal is to ignore these symbols so the length become 16.
All I can think is using for loops to check these symbols, but I think it is very hideous.
JS
function test() {
alert(document.getElementById("firstText").value.length);
}
HTML
<input type="text" id="firstText" />
<button onclick="test()">Submit</button>
You could use a regular expression to replace all non-word characters with the empty string, and check the length of the result:
const getLen = str => str.replace(/[^A-Za-z0-9]/g, '').length;
console.log(getLen('email_ex_3/2#mail.com'));
You can use the replace method by passing a regular expression as the second argument.
function test(){
alert(document.getElementById("firstText").value.replace(/[^a-zA-Z 0-9]+/g, "").length);
}
<input type="text" id="firstText"/>
<button onclick="test()">Submit</button>
You can do this
function test()
{
alert(document.getElementById("firstText").value.replace(/[\W_]+/g, "").length);
}
(/[\W_]) exclude all non-alphanumeric characters and /g for saying all

String Replace with Regex Decimal Validation fails in Javascript

I tried to restrict the user input with string.replace using Regular expression. But it fails, its not allow to enter any character. Kindly see the following HTML Page.
<!DOCTYPE html>
<html>
<head>
<title>Decimal Validation</title>
</head>
<body>
<p>A function is triggered when the user is pressing a key and on keyup in the input field.</p>
<input type="text" maxlength="9" onkeyup="myFunction(this)">
<script>
function myFunction(text) {
if(text) {
text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})/g, '');
}
}
</script>
</body>
</html>
I need to allow only the digits and precision (i.e., allow only one dot). If the user input is only a whole number then the length should be 9 or if the input is only decimal part then allow maximum 8 precision or if the mixture then allow decimal(9,5) - allow 4 digit and 5 precision.
The above said regular expression fails to validate, allow the char only digits and only one period.
A validation and a replacement are two different tasks, you need to test the field first and after to replace with something eventually. Example:
function myFunction(text) {
if( !/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})$/.test(text.value) ) {
text.value = ''; // or an other kind of replacement if you need something
// more precise
}
}
Note that you can also rewrite the pattern like this:
/^(?!\d*\.\d*\.)[\d.]{0,9}$/
To keep characters at the beginning that validate the pattern you can use this replacement:
text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8}).*/, '$1');

Add hashtag before each keyword

I am a newbie in coding JS and hope someone can guide me to the right direction of my keyword system. Below are the requirements for keyword text field's behavior.
Only non-symbol character (includes letter, digit and other countries' languages) and space are allowed. If any symbols are entered, it should be replaced by '' / the input text will not display the symbols.
the hash (#) should be added instantly when the first non-symbol character of keyword is entered.
the keyword is separated by a space
Below are my codes:
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([a-zA-Z0-9]+)/g, '#' + '$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeypress="hashtag();" />
The problem are, the hash (#) can only be added when I entered the second non-symbol character / a space, but not the first one. And, there is no handling for symbols' input and no hash added before other countries languages.
Thanks in advance!
Here's a snippet that should work. My changes are:
Use onkeydown instead of onkeyup to trigger the function. onkeydown fires before the letter has been inserted into the text field and so the function doesn't see the key you just typed.
Use [^a-zA-Z0-9]/g as the regex. ^ means "anything but", so basically you're removing everything except the characters listed there. You could also use [^\w]/g but that would also allow the underscore which may or may not want.
Add an extra step to preappend the # because the above step removes it. (may seem wasteful but it's elegant and plenty fast enough)
function hashtag() {
//get the current contents of the text field
var str = document.getElementById('tagid').value;
//strip any non-word characters (will also strip hash symbol)
str = str.replace(/[^a-zA-Z0-9]/g, '');
//add the hash symbol back
str = '#' + str;
//update the text field
document.getElementById('tagid').value = str;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeyup="hashtag();" />
For the first issue of the hash only being applied on the second press, you can use onkeyup="hashtag();" to execute the action after the keypress, once the text has been added to the input field and can then be evaluated.
Here is some documentation on JavaScript keypress events that may be helpful.
For removing symbols whilst still allowing foreign characters, I couldn't find anything great in pure js (PHP has ways to work around this which is interesting), so I've taken a different route of deleting all excluded characters (hopefully, if there's more please edit in to make more complete) and then "hash-tagging" everything else that isn't a space.
This would leave you with a function like this:
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Here's the complete code that you can run within the answer:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HashTag</title>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
</script>
</head>
<body>
Enter keyword: <INPUT TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"></input>
</body>
</html>
bind to onkeyup event
replace [a-zA-Z0-9]+ by \w+
for foreign symbols, you will have to add them one by one (I tried to put as many as I could find):
I added the i flag for your regex, you won't have to worry about uppercase letters like 'Â' as long as you have the lower case one
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([\wâàãäéèêëîìôòõòùûüñ]+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>
Edit :
not sure if you want to keep or remove special characters, here is a version were special chars are removed :
function hashtag() {
str = document.getElementById('tagid').value;
// remove things
str = str.replace(/[^\w ]/g, '');
tagged = str.replace(/(\w+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>

Categories

Resources