Comparing similar strings in jquery - javascript

How do I compare similar strings in jquery?
<script src="../../js/jq.js"></script>
<script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1==str2){
console.log('yep');
}
});
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
Comparing "One String" and "One String1" is not going to work if I'm only checking if the two values are equal. Is there any way to do this in jquery? For example I only want to compare 90% of the string.

You can see if one is contained inside the other for example:
if (str1.indexOf(str2) >= 0 || str2.indexOf(str1) >= 0)
console.log('yep');
}

Check this out : http://jsfiddle.net/Sj5dE/ You can comment out a,b block to see the similitude of the strings. It's of course case-sensitive. I hope this helps. Since your example talked about comparing two similar strings, I thought it'd be most likely that the beginning of the strings are the same so I didn't introduce any substring logic but feel free to change the function.

Try this it might work
<script src="../../js/jq.js"></script> <script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1===str2){ console.log('yep'); } });
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>

In javascript you can use the substring to get the 90% of the string you would like to compare.
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase().substring(0, 10);
var str2 = $.trim($('#str2').val().toUpperCase().substring(0, 10);
if(str1==str2){
console.log('yep');
}

look on
http://code.google.com/p/google-diff-match-patch/
the demo in
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html

You can check if the string is present or not by
$(".className").replace(/(^|\s)yourTextHere\S+/g, " ");

Related

How to remove characters when input not matches regex in JS

<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

Check a combination of string and integer using regex

I am trying to take input from the textbox now I want to show an alert if the textbox value matches with the regular expression.
I want to check "1702, Belgium" or "Belgium, 1702" using regex but I am getting null.
<script>
$(document).ready(function(){
var r =/+{1702}/;
var v=$(".a").val();
alert(v.match(r));
});
</script>
<body>
<input type="text" class="a" value="1702 Belgium"/>
</body>
Since we have only 2 strings need to be compared, Why cant we compare with array of constants("1702, Belgium" and "Belgium, 1702") instead of using regular expressions.
Comparing to regular expressions the above way is easy to understand.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var valuesToCompare = ["1702, Belgium", "Belgium, 1702"]
var v = $(".a").val().trim();
alert(valuesToCompare.includes(v));
// we can also use indexof to check
// alert(valuesToCompare.indexOf(v) !== -1);
});
</script>
<body>
<input type="text" class="a" value="1702, Belgium"/>
</body>
Consider the following example.
$(function() {
$("input.a").next("button").click(function(event) {
var currentValue = $("input.a").val();
var currentIndex = currentValue.indexOf("1702")
if (currentIndex >= 0) {
alert("1702 Found at " + currentIndex);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="a" value="1702 Belgium" /> <button>Check</button>
The .indexOf() will give you the position in the String that your string exists. It does the same for an Array. I have moved the code into a Click callback so you can test other strings or check it after something has been changed.

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(/(.*)-(.*)/).

How to go about parsing text for keywords in jQuery?

Say I had a famous speech posted on a website. What would be the best way to go about searching for a given keyword, say 'hello' throughout the entire document and save the number of occurrences as an integer? I don't really know where to start on this one. Should I use something like...
var wordcount;
$('#wrapper').each(function(e)
{
$("div:contains('hello')"){ //all content will be in the wrapper div
wordcount++;
});
});
I know that probably isn't right, but hopefully I'm on the right track. Thanks for the help!
The easiest way is to just return the length of a RegExp match:
var count = $("#wrapper div:contains('hello')").html().match(/hello/ig).length;
var numberOfMatches = $('div').text().match(/hello/ig).length;
Well unfortunately, that div:contains is only going to fire once. It is looking for all divs that contain that text. Unless you have every word wrapped in a div tag...
var text = $('#wrapper').text();
var words[] = text.split(' ');
var count = 0;
for(var i=0; i<words.length; i++){ if(words[i].IndexOf("TheWord") >= 0){ count++; } }
This is a non jquery method, but it should work for you.
If you're wanting to do this interactively (i.e., with a dynamic string), then this implementation is idiomatic:
http://jsfiddle.net/entropo/S5uTg/
JS ...
$("#keyword").keyup(function() {
var value = $(this).val(),
re = new RegExp(value, 'ig'),
count = $("#speech").text().match(re).length;
$("#result").text("Occurences: " + count);
});
HTML ...
<div id="search-form">
<legend>Search through this text</legend>
<label for="keyword">Keyword</label>
<input id="keyword" name="keyword" type="search"
placeholder="e.g. - today" required="" autofocus="" />
<div id="result"></div>
</div>

Categories