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

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

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 to match only if the both brackets are there in the string?

^[-+(]?\d+([,.]\d+)*([\)])*$
I am using the above regular expression for matching strings. one case i need to check
Testing string :
(111,1,1,1.3.3 should be failed
(111,1,1,1.3.3) should be passed
+1.1.1.1,1 should be passed
-1111 should be passed
-2,2,2,2.4.4 should be passed
2,3 should be passed
The above string is matching the regex, but i want to check if the string contains first bracket it should check for end match with bracket.
You can use ored regex here.
^(?:[+-]?\(\d+([,.]\d+)*\)|[+-]?\d+([,.]\d+)*)$
See demo.
https://regex101.com/r/hE4jH0/19
try this regex:
function validate(){
var regex = /^[-+(]?\d+([,.]\d+)*([\)])+/gi;
var value = document.getElementById("txtInput").value;
console.log(value);
document.getElementById("result").innerHTML = regex.test(value);
}
<input type="text" id="txtInput" value="(111,1,1,1.3.3">
<p id="result"></p>
<button onclick="validate()">Validate</button>

Regular expression. Find three words in the field

Help make the correct regular expression for the search 3 words into the field. So far I have done so, but I think it's crazy.
var inp = document.getElementsByTagName('input')[0],
button = document.getElementsByTagName('button')[0];
button.onclick = function() {
console.log(inp.value.match(/^([а-яa-z0-9]+ ){2}[а-яa-z0-9]+/i));
};
<input type="text" />
<button>Check</button>
I guess it's easier to split the text and then verify that the element count is as you expect it. You may want to trim the text before to avoid leading and trailing empty strings in the result array.
console.log(inp.value.trim().split(/\s+/))

Regex using .match in javascript brings the result more than once

I have this regex \w?(row-)\d+ and I'm trying to get bits from the html using javascript
so this is a part of my html:
<div class="col-md-1"><input class="form-control row-25 all" type="text" value="NA" onchange="validate('rep',this)" disabled></div>
<div class="col-md-1"><input class="form-control row-25 all" type="text" value="$15" onchange="validate('rep',this)" disabled></div>
<div class="col-md-1"><input class="form-control row-25" type="text" value="Per number" disabled></div>
and that's my js var rowIndex = element.className.match(/\w?(row-)\d+/);
What i'm getting from that .match function is this
row-25, row-
What I'm trying to get is only
row-25
What am i doing wrong here? Thanks.
UPDATE:
Actually I have found an answer to how to get what I need but that doesn't explain the output still, what I did is I chose to read rowIndex[0], and neglect the rest, however why is "row-" appearing anyway?
Because match() returns either null or an array of results. These results are the full pattern (\w?(row-)\d+) as well as the subpatterns (row-) represented by the bits enclosed within parentheses. That said, as it stands, your regular expression will also match classes like arrow-25 or row-25xyz. Here is a workaround if needed :
/(?:^|\s)(row-\d+)(?:\s|$)/
Dissection :
(...) captures subpattern
(?:...) doesn't capture subpattern
(?:^|\s) the beginning of the string or a whitespace
(row-\d+) "row-" plus at least one digit (subpattern 1)
(?:\s|$) a whitespace or the end of the string
If you want to extract only the number :
/(?:^|\s)row-(\d+)(?:\s|$)/
Dissection :
(?:^|\s) the beginning of the string or a whitespace
row- "row-"
(\d+) at least one digit (subpattern 1)
(?:\s|$) a whitespace or the end of the string
Usage example :
var r = /(?:^|\s)row-(\d+)(?:\s|$)/,
n = el.className.match(r);
if (n) { // if n is not null
n = n[1]; // set n as subpattern 1
}
With a class name like form-control row-25 all, n will be 25.
Also read :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
http://www.javascriptkit.com/javatutors/redev2.shtml
I you want to get row-25 use:
rowIndex = element.className.match(/\w?(row-\d+)/);
Change your regex to:
/\w?row-\d+/
Since your regex has this capturing group /(row-)/ therefore in the result you are getting 2 elements in the array:
Full matched input string
Captured group
Since you don't really need capturing group just don't put brackets around row-

Replace text in square brackets but not in the ones immediately after them

I have some HTML similar to this one:
<input value="" name="test[0][test_inner_one]" type="text">
<input value="" name="test[0][test_inner_two]" type="text">
<input value="" name="test[0][test_inner_three]" type="text">
What I'm trying to do is to replace only the 0 with something else, but I can't figure the regex.
So, for example, after replacing, it should look like:
<input value="" name="test[1][test_inner_one]" type="text">
<input value="" name="test[1][test_inner_two]" type="text">
<input value="" name="test[1][test_inner_three]" type="text">
The idea for the whole thing is I'm cloning HTML, and the 0 and the text before it will not be static, so for example it will not be always test[0] but it will be in the following format some_text[index][some_other_text], I need to replace only the "index".
Any help will be appreciated.
Looks like you can simply use this:
var newName = name.replace(/\[0]/, '[1]');
Or even more simply, get rid of the regular expression:
var newName = name.replace('[0]', '[1]');
Update
To replace any pairs of braces which contain only numbers, use something like this:
var newName = name.replace(/\[\d+]/, '[1]');
To replace only the content of the first pair of brackets, regardless of what it contains, you can use this
var newName = name.replace(/\[.*?]/, '[1]');
This works because the replace method will only replace the first match found (unless the g flag is enabled in your regular expression).
If you only want to replace the first occurence, simply let out the /g modifier:
var str = 'my[bar][string]';
str = str.replace(/\[.*?\]/, '[foo]');
console.log(str); //my[foo][string]
Autopsy:
\[ a literal [ character - we have to escape this as [ is a reserved regex char
.*? lazy match. Match as little as possible
\] a literal ] character - we have to escape this as ] is a reserved regex char

Categories

Resources