Javascript for matching text while typing - javascript

Basically, i need a code that constantly checks for how many times a particular string appears within a textarea everytime the user keys in a letter.
<textarea name="t_update" cols="50" rows="5" id="t_update" style="width:30%"
onKeyUp="check()" ></textarea>
<script>
function check(){
var cText = document.getElementById('t_update').value;
if (cText.match("abc")){
//Do something
}else{
//Do something else.
}
alert(cText.match("abc").length);
}
</script>
The current code i have only returns one even if i have a more than one match. Any help would be appreciated.

use match with a regular expression and a global
cText.match(/abc/g).length
//test
cText = "aaabbbbcccabcabchalloabc"
Firebug Console
cText = "aaabbbbcccabcabchalloabc" cText.match(/abc/g).length
>> 3

You can simply use split on your string like this:
function check(){
var cText = document.getElementById('t_update').value,
matches = cText.split('abc').length-1;
if (matches){
//Do something
}else{
//Do something else.
}
alert(matches);
}

Related

Regex number filtering from textarea

I have been looking for way how I could filter data within textarea using regex function for a quite a while now without any success. Below is the regex I want to use to filter UK telephone numbers.
(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?
Fiddle: https://jsfiddle.net/qdypo04y/
I want to achieve the result when the button is clicked it will remove lines which do not meet the regex? Alternatively would remove values which are not UK telephone numbers.
Any guidance would be appreciated.
Apart the use of textarea element your issue is:
how attach click event listener to your button (refer to: querySelector and addEventListener)
how get the content of textarea and split it into rows (refer to: textContent plus split and join)
finally how use your regex: refer to test
An example is:
document.querySelector('button').addEventListener('click', function(e) {
var txtArea = document.querySelector('textarea[rows="4"][cols="50"]');
var re = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var txtArr = txtArea.textContent.split('\n');
txtArr.forEach(function(ele, idx) {
txtArr[idx] = ele + ' test result is: ' + re.test(ele);
});
txtArea.textContent = txtArr.join('\n');
});
<textarea rows="4" cols="50">
+447222555555
0800 042 0213
2017/07/14
2017/07/17
2017/07/27
</textarea>
<button>Click me</button>
<script>
function myFunction() {
var regexp = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var content=$.trim($("textarea").val()).split('\n');
var result="";
for(var i = 0;i < content.length;i++){
if(regexp.test(content[i])){
result=result+content[i]+'\n';
}
}
$("textarea").val(result);
}
</script>
used JQuery to take the value from textarea

jquery if input contains phrase from array-child friendly global chat

I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter

Allow only roman characters in text fields

I am finding a way to make all the text boxes in the website only accept roman characters. Is there any easy way to do it globally.
Thanks in advance.
In modern browsers <input> accepts an attribute called pattern. This allows to restrict the valid characters in a given field.
input:invalid {
background-color:red;
}
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
For all other browsers you can find all form field via jQuery, check if a pattern-attribute exists, and check it against the value of a given field. You may also replace disallowed characters:
$('form').on('keyup blur','input',function() {
if ($(this).val() && $(this).attr('pattern')) {
//var pattern = new RegExp('^'+$(this).attr('pattern')+'$', 'g');
//$(this).toggleClass('invalid', pattern.match(!$(this).val()));
var pattern = new RegExp($(this).attr('pattern').replace(/\[/,'[^'), 'g');
$(this).val($(this).val().replace(pattern,''));
}
});
input:invalid {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
Oh, you still want to validate form inputs on the server-side. All HTML- or Javascript-stuff does not prevent all visitors of your site to submit broken stuff.
I will refer to the marked answer for the following question for the regex which filters out non-roman characters:
How to detect non-roman characters in JS?
Spoiler: the regex is /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g
Now all you need is a little bit of tinkering with jQuery:
var myInputId = "#foo"; // Or whatever you wish to use.
var input = $(myInputId);
var exp = /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g;
input.blur(function() {
input.value = input.value.replace(exp, "");
});
Include this snippet into your master page for example:
<script>
$(function(){
$('input[type=text],textarea').keypress(function(e){
var char = String.fromCharCode(e.which || e.charCode);
var rgx = /[\u0000-\u007F]/;
if (rgx.test(char) == false)
return false;
})
})
</script>
Here is my idea based on #fboes answer.
I also needed to show user whats wrong, so there is error message showing but with no redundancy when typing couple of forbidden characters in a row.
//I wanted first to assign pattern attr to every input in form but when it's happening, all "\" chars are removed from regex therefore - it doesn't work, so I had to add it in templates for every input.
let isIncorrect = false;
scope.checkPattern = function(e) {
// I don't want to allow Chineese, cyrylic chars but some other special - yes
var pattern = new RegExp('[a-zA-Z\s\.\-_äÄöÖüÜßąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+', "g");
if ($(e).is(':valid')){
return true
} else {
$(e).val($(e).val().replace(pattern,''));
return false
}
};
scope.removeAlert = function (e){
$(e).parent().find('.text-danger').remove();
isIncorrect = false;
}
// unallowed characters in order inputs
$('.my-form').on('keyup blur','input',function(e) {
if (!scope.checkPattern($(this))) {
if (!isIncorrect){
// show this error message but only once (!) and for specified period of time
$(this).parent().append('<p class="text-danger">Only latin characters allowed</p>');
isIncorrect = true;
}
setTimeout(scope.removeAlert, 3000, $(this));
}
});

Replace the contents of a div with regex match of string

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.
<html>
<body>
<script type="text/javascript">
function search(){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.replace(document.getElementById("results"),
(str.match(patt1))));
}
</script>
</body>
<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>
Any ideas as to why it's not working?
You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )
In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.
// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
// This line stops the default action occurring
e.preventDefault();
}
Note: we don't need to specify an argument here, e goes in automatically
<button name="Search" onclick="search()">Click Here</button>
Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.
Try something like this instead:
function search(){
var str = "Visit W3Schools";
var patt1=/w3schools/i;
document.getElementById("results").innerHTML=(str.match(patt1))[0];
}
document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:
function search() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
}

Javascript functions

So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/

Categories

Resources