Unable to match strings with jQuery with blank space - javascript

I am trying to match a string inside another but I am not able to do it:
I want to match a string based on another string that I am typing but I get "false" when I "ask" if "Aston Martin" starts with "Aston ".
EDIT:
Note that the filter is a "as you type", and in this case, I have a blank space in the end of "Aston ".
IMPORTANT NOTE:
Based on #mplungjan answer, I had another issue regarding the blank space at the end of the filter string. Testing it, I was getting the charCode 160, so the solution I used was applying the replace to both strings:
.replace(String.fromCharCode(160), ' ')
var value = $("#brand").text();
var brand = $("#filter").val();
alert(brand.substr(0, value.length).toUpperCase() == value.toUpperCase());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

Using indexOf == 0 will show the string beginning with the brand INCLUDING the space in the value!
var brand = $("#brand").text();
var value = $("#filter").val();
console.log(">"+brand+"<",">"+value+"<",brand.toUpperCase().indexOf(value.toUpperCase())==0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">
Onkeyup:
$("#filter").on("keyup", function() {
var brand = $("#brand").text();
brand = brand?brand.toUpperCase():"";
var value = $("#filter").val();
value = value?value.toUpperCase():"";
if (brand && value) {
console.log(brand, value,brand.indexOf(value) == 0); // same as regex /^word /
}
else {
console.log("Something is empty");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

This will work, and dont forget you have a space in the value of the input?
var value = $("#brand").text();
var brand = $("#filter").val();
alert(!!value.toUpperCase().match(brand.toUpperCase()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

You can try it like this:
x = "Aston Martin";
if (x.match("Aston")) {
// Code
}
Update1:
And if you want that your string should starts with specific word and you want to match space at end you can do this:
if(x.match(/^Aston /)) {
}

please use this one :
value.toUpperCase().indexOf(brand.toUpperCase())>=0?true:false

Related

How to input phone no in this 'xxx-xxx-xxxx' format in number input field

I want that whenever I type a number in the number input field in XXXXXXXXXX format it takes as XXX-XXX-XXXX using HTML, CSS and javascript.
Just like this snippet but without using the mask script.
$('.phone_us').mask('000-000-0000');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<input type="text" class="phone_us" />
There are some working answers here, but this solution is more stable.
Using the oninput event for instant replace and ...
Applying regex on the full string, to allow copy/paste, and finally ...
This code is shorter as well:
$('.phone_us').on('input', function() { //Using input event for instant effect
let text=$(this).val() //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
$(this).val(text); //Set the new text
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Or even without jQuery:
document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
let text=this.value //Get the value
text=text.replace(/\D/g,'') //Remove illegal characters
if(text.length>3) text=text.replace(/.{3}/,'$&-') //Add hyphen at pos.4
if(text.length>7) text=text.replace(/.{7}/,'$&-') //Add hyphen at pos.8
this.value=text; //Set the new text
});
<input class="phone_us" maxlength="12">
you could try like this
$(document).ready(function () {
$(".phone_us").keyup(function (e) {
var value = $(".phone_us").val();
if (e.key.match(/[0-9]/) == null) {
value = value.replace(e.key, "");
$(".phone_us").val(value);
return;
}
if (value.length == 3) {
$(".phone_us").val(value + "-")
}
if (value.length == 7) {
$(".phone_us").val(value + "-")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
<form id="form1" runat="server">
<input type="text" maxlength="12" class="phone_us"/>
</form>
You can implement like this
document.getElementById('txtphone').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});txtphone
<input type="text" class="phone_us" id="txtphone" placeholder = "(000) 000-0000"/>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
Use HTML5 input type=tel to get phone number, and pattern attribute to specify any pattern.
[0-9]{3} represent the 0-9 numeric and 3 digits.
Then, add a hyphen (-), and use the numerics pattern again.
You can use own pattern and your country wise pattern like
[1-9]{4}-[1-9]{6} for the format 1234-567890.
Use the min-length and max-length in HTML5 to set limit.
Note that these patterns won't automatically add the hyphens, but will only allow correctly formatted input.
If you want get more patterns, search on web or see HTML5pattern.com
Pure javascript.
Enter 10 digits in the input field and click anywhere outside the input field.
var myTel = document.getElementById("tel");
myTel.addEventListener("blur", function() {
var str=myTel.value;
var pattern=/[0-9]{10}/;
if (pattern.test(str)) {
newstr=str.slice(0,3)+'-'+str.slice(3,6)+'-'+str.slice(6,10);
myTel.value=newstr;
}
else {
// bad
myTel.value='bad value: only 10 digits';
}
})
<form>
<input type="text" id="tel" name="tel" maxlength='10'>
</form>

compare Two field if the field is in the content of other field using javascript after submit button clicked

Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online

Add a digit to the end of multiple attributes

I'm trying to grab the end digit of the target div, replace and join two attributes (js-data-reveals) with that digit added at the end (_1).
I know it has something to do with the regular expression that I am using to replace the attributes but I can't figure it out.
Hope you can help.
$('#js-form-group-UPLOAD_DOCUMENT_ID_1').find('input').each(function() {
var attrName = 'js-data-reveals';
var $el = $(this);
//Get Last Digit from ID
var idNumber = $el.attr('id').match(/\d+$/);
var attrs = $el.attr(attrName);
//Split the two attributes in js-data-reveals
var data = attrs.split(',').map(function(item) {
return item.replace(/.{0}$/, function(idNumber) {
return idNumber
});
});
$el.attr(attrName, data.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
<fieldset>
<input type="file" class="form-control" id="UPLOAD_DOCUMENT_ID_1"
js-data-driven="true"
js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION">
</fieldset>
</div>
match() returns an array.
Can simplify this using attr(attrName, function)
$('input[js-data-reveals]').attr('js-data-reveals', function(_, existing) {
var idNumber = this.id.match(/\d+$/)[0];
return existing.split(',').map(function(s) {
// replace number if it already exists or add it if it doesn't
return s.match(/_\d+$/)
? s.replace(/\d+$/, idNumber)
: s += '_' + idNumber;
}).join();
});
console.log($('#UPLOAD_DOCUMENT_ID_1').attr('js-data-reveals'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
<fieldset>
<input type="file"
class="form-control"
id="UPLOAD_DOCUMENT_ID_1"
js-data-driven="true"
js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION_999">
</fieldset>
</div>
Remove the '+' in your Regular Expression to make it:
var idNumber = $el.attr('id').match(/\d$/);
The '+' makes a Regular Expression match the given character 1 or more times, so \d+$ would match 12345 in 'd12345'. Since you only want the last digit to match, removing the '+' will make it works as expected.

Displaying new input value (adding spaces)

This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

Validate input field and block characters

Hello guys i have an input field and i want to validate in real time the insterted characters.
I want that this input field accept only letters, number and one blank space. If is inserted for example *, script delete this characters.
Regards
On input filed:
onkeyup="check(this,'onlyletter')" onblur="check(this,'onlyletter')
On JS:
var r={
'onlyletter': // i need correct regular expression
}
function check(o,w){
// i need function
}
I have: Abc123' 123* but i accept Abc123 123
with raw JS:
the clue is in the method transform
<html>
<head>
<script>
function transform(elem) {
var v = elem.value;
var n = "";
//loop it to cut of more than 1 -- e.g. on copy & paste
if(v.length) {
n = v.slice(-1);
if( !isNaN(parseFloat(n)) && isFinite(n) ) {
elem.value = v.substring(0, v.length - 1);
}
}
}
</script>
</head>
<body>
<input
type="text"
name="date"
placeholder="Text only!"
onkeyup="transform(this);"
maxlength="10"
>
</body>
</html>
alternate way using jquery
MASK the textfield to only accept letters. now that can be done a number of ways. one is the query mask plugin
you only need query, query-mask and then it is 1 line of code ;)
demo:
<html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mask.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//masked input for alphabets only
//constrained to 20 characters in length without spaces
$("#myTextField").mask("SSSSSSSSSSSSSSSSSSSS");
});
</script>
<body>
<br><input type = "text" id="myTextField" name="Text Field"></br>
</body>
</html>

Categories

Resources