Search text no matter if is in lower or upper case - javascript

I have a function that I use to search content in my web using one text box <input class="form-control" id="search" type="text" placeholder="Search" /> the showing content are in different panels, so this is my script.
$('#search').keyup(function () {
var term = $(this).val();
if (term != '') {
$('.panel').hide();
$('.panel').filter(function () {
return $(this).text().indexOf(term) > -1
}).show();
} else {
$('.panel').show();
}
});
That works fine but only with the exactly match, if I write in the text box Hello shows me only the Hello words but I need that shows me to hello, hEllO or HELLO, all the string no matter the lower or upper case.
Any help is really appreciated, sorry for my bad grammar.

Convert both the search string and the text you are searching in to lower case:
return $(this).text().toLowerCase().indexOf(term.toLowerCase()) > -1
More info on MDN

Try to use toLowerCase() function to by pass case-sensitive matching, like:
$(this).text().toLowerCase().indexOf(term.toLowerCase()) > -1

use .toUpperCase() both your input val and filter val

Related

Search all words in the input field, then replace all matching words in the div tag

$('#srctxt div').each(function() {
var dari = $('#box').val();
var text = $(this).text();
$(this).html(text.replace(dari, '<b>'+dari+'</b>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="POST">
<input type="text" id="box" value="love"> // working
<input type="text" id="box" value="love girl"> // not working
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
</form>
I'm developing a search site by bolding every matching word of the input word with search results.
If only a word is entered, such as the word love, then this script works quite well. But if using two or more words, then this script does not work properly.
for example the word love girl, then the bold on the results for only one line. but it all contains the word love, so this is a problem for me.
sorry if my English is a bit hard to understand. however, I am asking for suggestions of this jQuery code fix. Thank you...
You can easily do this using regex
Here are the steps:
Step-1. Split the input value to make an array of input words.
Step-2. Iterate over all the div for which you want to execute search/replace condition
Step-3. For each word in input array create a searchregexp and replace if found
if ($('#box').val().length !== 0) {
var dari = $('#box').val().split(' ');
$('#srctxt div').each(function() {
dari.map(item => {
var regex = new RegExp('(' + item + ')(?!>|b>)', 'gi');
$(this).html($(this).html().replace(regex, "<b>$1</b>"));
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box" value="love girl b">
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
Also I removed the duplicate input field having same id as it is invalid html.
I think you will have to loop through your text in the search field. Assuming no special characters (-,{,}, > etc) are entered you can do following
$('#srctxt div').each(function() {
var dari = $('#box').val().split(" ");
var text = $(this).text();
dar.map((val, index) => {
$(this).html(text.replace(val, '<b>'+val+'</b>'));
});
});
Let me know if this helps.
maybe you have to split your search query, like:
'love girl'.split(' '); // ---> ['love','girl'];
and do a forEach on the resulting array and behave each one like your dari variable.
note that even if your word is one word, (like "love"), the result of split would still be an array. so you do not need to separate your logic into two branches.

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 multiple <br>'s with only one <br>

How do I use JavaScript to detect
<br>
<br>
<br>
to become one
<br>
?
I tried with:
jQuery('body').html().replace(/(\<br\>\r\n){3, }/g,"\n");
but this is not working for me.
CSS Solution
If you want to disable the effect of multiple <br> on the page, you can do it by CSS without using JavaScript:
br + br { display: none; }
Check the jsFiddle demo.
However, this method is ideal when you are working with tags, something like this:
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
<div>Text</div><br /><br /><br />
In other cases, like this:
Hello World<br /> <br />
Hello World<br /> <br />
Hello World<br /> <br />
It will fail (as CSS passes text nodes). Instead, use a JavaScript solution.
JavaScript Solution
// It's better to wait for document ready instead of window.onload().
window.onload = function () {
// Get all `br` tags, defined needed variables
var br = document.getElementsByTagName('br'),
l = br.length,
i = 0,
nextelem, elemname, include;
// Loop through tags
for (i; i < l - 1; i++) {
// This flag indentify we should hide the next element or not
include = false;
// Getting next element
nextelem = br[i].nextSibling;
// Getting element name
elemname = nextelem.nodeName.toLowerCase();
// If element name is `br`, set the flag as true.
if (elemname == 'br') {
include = true;
}
// If element name is `#text`, we face text node
else if (elemname == '#text') {
// If text node is only white space, we must pass it.
// This is because of something like this: `<br /> <br />`
if (! nextelem.data.replace(/\s+/g, '').length) {
nextelem = br[i+1];
include = true;
}
}
// If the element is flagged as true, hide it
if (include) {
nextelem.style.display = 'none';
}
}
};
Check the jsFiddle demo.
What is the point of sending HTML, which is in a form that you don't want, to the client browser and making it run JavaScript code to clean it up? This looks like a bad design.
How about fixing all your static HTML, and HTML generation, so that these superfluous <br> elements do not occur in the first place?
If you use JavaScript to modify the document object, do so for dynamic effects that cannot be achieved in any other way.
Simpler:
var newText = oldText.replace(/(<br\s*\/?>){3,}/gi, '<br>');
This will allow optional tag terminator (/>) and also spaces before tag end (e.g. <br /> or <br >).
Wouldn't something like this be the right approach:
$("br~br").remove()
EDIT: No, it's wrong, because its definition of "contiguous" is too loose, as per BoltClock.
This solution is jQuery + DOM only, does not manipulate HTML as string, works with text nodes, ignores whitespace only text nodes:
$('br').each(function () {
const {nodeName} = this;
let node = this;
while (node = node.previousSibling) {
if (node.nodeType !== Node.TEXT_NODE || node.nodeValue.trim() !== '') {
break;
};
}
if (node && node !== this && node.nodeName === nodeName) {
$(node).remove();
}
});
See: https://jsfiddle.net/kov35jct/
Try this
$('body').html($('body').html().replace(/(<br>)+/g,"<br>"));
It will replace n number of <br> into one.
Demo
I would go with this:
$('body').html($('body').html().replace(/<br\W?\\?>(\W?(<br\W?\\?>)+)+/g,"<br>"));
However, after reading the comments in another post here I do consider that you should try to avoid doing this in case you can correct it in the back end.
A lot of the other answers to this question will only replace up to certain amount of elements, or use complex loops. I came up with a simple regex that can be used to replace any number of <br> tags with a single tag. This works with multiple instances of multiple tags in a string.
/(<br>*)+/g
To implement this in JavaScript, you can use the String.replace method:
myString.replace(/(<br>*)+/g, "<br/>");
To replace multiple <br/> tags, add a / to the regex:
/(<br\/>*)+/g
Try this:
jQuery('body').html(
jQuery('body').html().replace(/(?:<br>\s+){3,}/ig,"\n"));
);
DEMO:
jsfiddle

displaying user content as typed in

When a user types in some value in a text box it should be displayed in a td as it is.
This is the code I've tried with a div,
<input type="text" name="userStr" id="userStr" onKeyUp="processValue()"/>
<div id="disp">
</div>
<script type="text/javascript" >
function processValue() {
var userval = document.getElementById("userStr").value;
//alert('userval'+userval);
document.getElementById("disp").innerHTML = userval;
}
I enter the value, &lt&gt &#40 &#41 &#35 &#38 , but it is showing as <> ( ) # &
instead of the original string (&lt&gt &#40 &#41 &#35 &#38 )
What is the standard way to do this.
While I typed stackoverflow showed exactly the same, I'll now view the source, but looking for insights from you.
Thanks.
Try:
document.getElementById("disp").innerHTML = userval.replace(/&/g, '&').replace(/</g, '<');
Alternatively, you could set the element text, but you'd have to deal with browser variation.

Categories

Resources