Related
Here is my test code:
<div id="scrollable" style="width:100%; height:100px; overflow: scroll">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque dolorum esse,
illum nostrum placeat quia? Animi corporis explicabo modi neque porro possimus
quos totam. Accusamus ad aliquam animi, aperiam atque beatae consectetur
debitis deleniti dignissimos doloremque doloribus ducimus ea error est eveniet
fugit id iste itaque mollitia nostrum officia omnis optio quam quidem saepe
sapiente ullam voluptatibus. A ad aliquam at aut, blanditiis commodi
consectetur consequuntur delectus dignissimos ducimus ea esse est fuga fugiat,
fugit illo inventore ipsa iusto laboriosam libero minima minus nesciunt nulla
officia quaerat quam quidem quo recusandae reprehenderit similique soluta
tempora, temporibus ut vel veritatis vero voluptatem. Ab culpa dolore eveniet
exercitationem explicabo incidunt itaque laudantium molestiae nisi nobis
nostrum, numquam possimus quam, quas quis, quisquam recusandae sed voluptatem.
Deleniti esse iure nisi odio ullam. Autem ducimus eius enim inventore placeat
possimus repudiandae voluptates? A adipisci cumque doloribus eligendi, eos
eveniet harum laborum minus nam optio quae sed voluptas voluptates.
Accusantium architecto, at dolor dolore eligendi incidunt ipsa, ipsum iure
mollitia, nam nesciunt quo repellendus reprehenderit rerum sapiente similique
voluptas. Eos laborum optio quibusdam voluptatum. Deserunt dolor doloribus
enim minus praesentium reiciendis soluta tenetur. Ad consectetur consequuntur
cumque iure molestias nam perferendis placeat quibusdam soluta, voluptatum!
</div>
<script
type="text/javascript"
src="../node_modules/jquery/dist/jquery.js"
></script>
<script>
var scrollable = document.querySelector("#scrollable");
$(scrollable).on("scroll", ev => {
console.log(`container scroll top:${$(scrollable).scrollTop()}`);
console.log(`container scroll height:${$(scrollable).height()}`);
});
</script>
I'm confused, when i scroll to scrollable div bottom, the scroll top != scroll height
This should be correct.
container scroll height is the height of the window.
container scroll top is how far from the top of the content you've scrolled.
So if I load your content in my browser, and the container scroll height = 100, and I make the window narrower, then my container scroll height is still 100, I haven't changed the height of the window. But now you can scroll further down, so your container scroll top could change as you scroll further down.
I'm trying to create a scroll indicator regarding a single HTML element. In my page I have a paragraph with overflow set to "scroll".
Problem is, I tried many methods and each of them only seem to work on the "main" scroll event of the whole page.
Following is my adaptation of the code found at:
https://www.w3schools.com/howto/howto_js_scroll_indicator.asp
I assigned the class name "content" to my < p >.
<script>
window.body.getElementsByClassName("content").onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.getElementsByClassName("content").scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
Gave this a shot to no avail, unfortunately.
That may be due to the fact I'm still learning.
Attached is also a preview of the current page.
As you can see, the grey scroll indicator is on top of it but it doesn't work when I scroll through the paragraph (< p >).
It may be quite simple but I can't figure this out.
<div class="header">
<div class="progress-container">
<div class="progress-bar" id="myBar"></div></div></div>
<a class="content">Lorem ipsum dolor sit amet, consectetur adipisci elit, sed do eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrum exercitationem ullamco laboriosam, nisi ut aliquid ex ea commodi consequatur. Duis aute irure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? [33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.<br>
Thank you in advance!
So...
been manipulating my code a little bit.
This is what I found to work:
I assigned an id to my element, in this case "par".
I assigned " onscroll="myFunction()" " to my element.
(Optional) I assigned a class to style my element.
And then I inserted a javascript function inside my html file as a script (you can have a separate .js file, if you prefer so) with the following code. Keep in mind you must refer to your element with the same ID
< a class="content" onscroll="myFunction()" id="par">Your paragraph content < /a >
<script>
function myFunction() {
var winScroll = document.getElementById("par").scrollTop || document.getElementById("par").scrollTop;
var height = document.getElementById("par").scrollHeight - document.getElementById("par").clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.width = scrolled + "%";
}
</script>
Hope this will clear some doubts about my question. This may look uber-simple to some of you but it wasn't on my part. Have a nice day!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have got my header position: fixed; and height: 200px; and green color in the main position up in the website. How can I reduce the height to 100px; if when I scroll down the web page?
I has made some small JSFIDDLE so you can see it. http://fiddle.jshell.net/#&js=ybR4h7OViQ
The header is set up with 200px height. I just want to know what JS/Jquery code do I need to add here so it can go.
Are you looking for something like this?
$(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 5)
$("header").addClass("small");
else
$("header").removeClass("small");
});
});
* {margin: 0; padding: 0; list-style: none; font-family: 'Segoe UI';}
body {padding-top: 100px;}
p {margin: 0 0 10px;}
header {height: 100px; line-height: 100px; text-align: center; background-color: #ccf; position: fixed; left: 0; top: 0; right: 0; transition: all 0.5s ease;}
header.small {height: 50px; line-height: 50px;}
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<header>
<h1>Hello</h1>
</header>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus aliquam fugiat corporis ratione. Eius maiores qui unde aperiam officia, dolorum quo, hic animi harum natus optio adipisci ipsa ratione totam.</p>
<p>Pariatur repellendus repellat, dolores odio reprehenderit provident culpa nostrum molestias optio officia magni impedit iusto? Repellendus fugit est, dicta, non voluptatum similique perspiciatis facilis voluptates magnam. Veritatis iste quis corporis?</p>
<p>Repellat totam deleniti officia sunt amet nisi libero ad, sint quidem, inventore sequi dolorum quae cum suscipit, molestias eum velit quod cupiditate. Soluta doloremque quis laboriosam unde ad laudantium praesentium.</p>
<p>Laborum ab asperiores sequi, placeat expedita. Optio nostrum soluta temporibus numquam repellendus expedita, impedit ducimus reiciendis laudantium minima nobis harum adipisci labore vitae earum magni quo animi facere. Quas, fugit!</p>
<p>At excepturi eius architecto dolorum aliquid. Ex ullam repellendus non id nulla modi quasi numquam, consectetur nam! Cum tempora quisquam, officiis. Atque ipsa culpa saepe, officiis modi error tempora sint!</p>
<p>Ab minus, tempore! Modi nemo praesentium voluptatibus accusamus sit doloremque dignissimos facere illo dolor! Dicta hic consequatur sint voluptatum necessitatibus similique fugit culpa modi eius ab, maiores quam ipsa officia.</p>
<p>In vero minus, dolorum deserunt voluptatibus accusamus, mollitia quasi, sapiente dicta distinctio explicabo cupiditate autem nisi placeat dolores odit harum molestiae aspernatur! Porro, optio vero dolorum architecto cumque incidunt quasi!</p>
<p>Pariatur blanditiis et quod officiis illo iste numquam, temporibus, in neque doloremque. Facere dignissimos exercitationem nisi veritatis possimus vitae debitis quas animi natus excepturi fugit repellat, porro, voluptatum aliquid reiciendis.</p>
<p>Facere, laudantium. Eaque reprehenderit laudantium distinctio quos, in obcaecati fuga. Quia provident, temporibus voluptates, totam delectus nesciunt corrupti optio et voluptatem possimus facere tempore ad quod vel soluta velit itaque?</p>
<p>Quisquam, itaque tenetur accusantium nemo temporibus odit, id qui atque ab magnam sunt voluptas soluta deserunt impedit neque amet nesciunt eaque unde dignissimos. Sequi eligendi, quos consectetur, laborum commodi maxime.</p>
<p>Temporibus et facilis, ipsum aspernatur omnis provident aliquam illum neque laboriosam libero voluptatum voluptates dicta labore ut saepe harum consequuntur eligendi facere quibusdam dolores, ex reiciendis enim aut, impedit! Tempora.</p>
<p>Beatae, ullam, odit. Animi, maiores facere fuga et. Laborum quae sequi veritatis, incidunt dignissimos dolorem, labore, error maxime quam ullam modi fugit accusantium possimus architecto id blanditiis pariatur aperiam ducimus?</p>
<p>Illum magni porro consequatur veritatis earum. Illum delectus, earum quidem error facilis animi ad aperiam temporibus, nesciunt cum nemo fuga quod, assumenda alias ipsum atque. Animi beatae aliquid, voluptatum ratione!</p>
<p>Tempore architecto enim quibusdam, aperiam reprehenderit. Culpa laboriosam commodi ipsum cumque, suscipit cupiditate! Earum repellat totam quo eaque vitae, numquam natus laborum reprehenderit hic, rerum illo, nostrum nobis id. Odio?</p>
<p>In accusamus voluptatum alias doloremque repellat, minima at fugiat commodi praesentium perspiciatis similique quaerat, iste quibusdam, a consectetur ullam modi quod maiores nihil quam velit maxime ad. Ipsum, aut, architecto.</p>
Just do it like this:
var heightFromTop = 50, //Height from top where header will shrink
headerHeight = 100, //height that header will shrink to.
header = document.querySelector(".header"), //Selects .header element
defaultHeight = getComputedStyle(header).height; //Gets the default height of the element
window.onscroll = function() { //Runs function when you scroll window
if (document.documentElement.scrollTop > heightFromTop) header.style.height = headerHeight + "px"; //Checks if the body is scroll down more then heightFromTop
else header.style.height = defaultHeight + "px"; //Otherwise, set it to the default height
}
JSFiddle Demo
I want to have 2 divs sized to a particular width (i.e. 500px). One above the other aligned horizontally.
The top box should hide its scroll bar, the bottom should show a scroll bar and when the user scrolls I'd like the offset of the top box to change to the value of the bottom box. So that when the bottom DIV scrolls horizontally it appears that the top DIV is also scrolling in unison.
I'm happy to do this in Jquery if it makes the process easier.
$('#bottom').on('scroll', function () {
$('#top').scrollTop($(this).scrollTop());
});
Here we are using .scrollTop() for all it's worth, getting the scrollTop value from the element with scroll-bars, and setting the scrollTop for the other element to sync their scroll positions: http://api.jquery.com/scrollTop
This assumes that your bottom element has an ID of bottom and your top element has an ID of top.
You can hide the scroll-bars for the top element using CSS:
#top {
overflow : hidden;
}
Here is a demo: http://jsfiddle.net/sgcer/1884/
I suppose I've never really had a reason to do this, but it looks pretty cool in action.
I know this is an old thread, but maybe this will help someone.
In case if you need to synchronize scrolling in double direction, it's not good enough to just handle both containers' scrolling events and set the scroll value, because then scrolling events are getting into cycle and the scrolling is not smooth (try to scroll vertically by a mouse wheel an example given by Hightom).
Here is an example of how you can check if you are already synchronizing the scroll:
var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;
var leftDiv = document.getElementById('left');
var rightDiv = document.getElementById('right');
leftDiv.onscroll = function() {
if (!isSyncingLeftScroll) {
isSyncingRightScroll = true;
rightDiv.scrollTop = this.scrollTop;
}
isSyncingLeftScroll = false;
}
rightDiv.onscroll = function() {
if (!isSyncingRightScroll) {
isSyncingLeftScroll = true;
leftDiv.scrollTop = this.scrollTop;
}
isSyncingRightScroll = false;
}
.container {
width: 200px;
height: 500px;
overflow-y: auto;
}
.leftContainer {
float: left;
}
.rightContainer {
float: right;
}
<div id="left" class="container leftContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
<div id="right" class="container rightContainer">
Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</div>
Here is the fiddle.
I've been looking for a double direction solution and thanks to you all, your contibutions helped me doing this :
$('#cells').on('scroll', function () {
$('#hours').scrollTop($(this).scrollTop());
$('#days').scrollLeft($(this).scrollLeft());});
See on JSFiddle : https://jsfiddle.net/sgcer/1274/
Hope it's help someone someday :-)
Alright, so I evaluated all of the options presented here, and they all had limitations of one form or another:
The accepted answer suffers from known issues using the mouse scroll wheel.
The next highest upvote does not have scroll wheel issues, but only works for two known elements. If you need more elements, it's not scalable.
The only solution that showed promise was Lacho's, but there were known element references in the code that were not included in the snippet. On the plus side, it had the structure needed for performance, and it's in TypeScript.
I leveraged that to create a reusable version that can work with an unlimited number of elements, and it doesn't require JQuery.
function scrollSync(selector) {
let active = null;
document.querySelectorAll(selector).forEach(function(element) {
element.addEventListener("mouseenter", function(e) {
active = e.target;
});
element.addEventListener("scroll", function(e) {
if (e.target !== active) return;
document.querySelectorAll(selector).forEach(function(target) {
if (active === target) return;
target.scrollTop = active.scrollTop;
target.scrollLeft = active.scrollLeft;
});
});
});
}
//RWM: Call the function on the elements you need synced.
scrollSync(".scrollSync");
You can check out the JSFiddle for this here: http://jsfiddle.net/gLa2ndur/3. You can see it uses both horizontal and vertical scrolling examples.
The only known limitation is that it might not work on divs of different sizes. I'm sure someone can work on incorporating Andrew's work into this if your use-case finds that necessary (mine does not).
I hope this is helpful to someone!
Another solution that prevents this looping problem and achieves a smooth scroll.
This makes sure that only the focused element gets the scroll event.
let activePre: HTMLPreElement = null;
document.querySelectorAll(".scrollable-pre").forEach(function(pre: HTMLPreElement) {
pre.addEventListener("mouseenter", function(e: MouseEvent) {
let pre = e.target as HTMLPreElement;
activePre = pre;
});
pre.addEventListener("scroll", function(e: MouseEvent) {
let pre = e.target as HTMLPreElement;
if (activePre !== pre) {
return;
}
if (pre !== versionBasePre) {
versionBasePre.scrollTop = pre.scrollTop;
versionBasePre.scrollLeft = pre.scrollLeft;
}
if (pre !== versionCurrentPre) {
versionCurrentPre.scrollTop = pre.scrollTop;
versionCurrentPre.scrollLeft = pre.scrollLeft;
}
});
});
Thanks to the answers above, I made a mixed solution that works preferentially for me:
var isLeftScrollTopCalled = false;
$('#leftElement').scroll(function (e) {
if (isRightScrollTopCalled) {
return isRightScrollTopCalled = false;
}
$('#rightElement').scrollTop($(this).scrollTop());
isLeftScrollTopCalled = true;
});
var isRightScrollTopCalled = false;
$('#rightElement').scroll(function (e) {
if (isLeftScrollTopCalled) {
return isLeftScrollTopCalled = false;
}
$('#leftElement').scrollTop($(this).scrollTop());
isRightScrollTopCalled = true;
});
I noticed that his question was pretty old, but I thought I could leave a jQuery implementation that works much better than using timers. Here, I am using two event listeners like the previously used solutions but, this will use proportions/percentage to sync scrolls for two differently sized div boxes. You can apply this same knowledge to get the position the scrollbars to a Vanilla JS solution. This will make the scrolling between the two divs much smoother.
/** Scroll sync between editor and preview **/
// Locks so that only one pane is in control of scroll sync
var eScroll = false;
var pScroll = false;
// Set the listener to scroll
this.edit.on('scroll', function() {
if(eScroll) { // Lock the editor pane
eScroll = false;
return;
}
pScroll = true; // Enable the preview scroll
// Set elements to variables
let current = self.edit.get(0);
let other = self.preview.get(0);
// Calculate the position of scroll position based on percentage
let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);
// Set the scroll position on the other pane
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});
this.preview.on('scroll', function() {
if(pScroll) { // Lock the preview pane
pScroll = false;
return;
}
eScroll = true; // Enable the editor scroll
// Set elements to variables
let current = self.preview.get(0);
let other = self.edit.get(0);
// Calculate the position of scroll position based on percentage
let percentage = current.scrollTop / (current.scrollHeight - current.offsetHeight);
// Set the scroll position on the other pane
other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
});
I'm trying to get a case-insensitive search with two strings in JavaScript working.
Normally it would be like this:
var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
The /i flag would be for case-insensitive.
But I need to search for a second string; without the flag it works perfect:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
If I add the /i flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
How can I achieve this?
Yeah, use .match, rather than .search. The result from the .match call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf like this:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
Replace
var result= string.search(/searchstring/i);
with
var result= string.search(new RegExp(searchstring, "i"));
If you're just searching for a string rather than a more complicated regular expression, you can use indexOf() - but remember to lowercase both strings first because indexOf() is case sensitive:
var string="Stackoverflow is the BEST";
var searchstring="best";
// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();
var result = lcString.indexOf(lcSearchString)>=0;
alert(result);
Or in a single line:
var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;
Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:
Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.
Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);
ES6+:
let string="Stackoverflow is the BEST";
let searchstring="best";
let found = string.toLowerCase()
.includes(searchstring.toLowerCase());
includes() returns true if searchString appears at one or more positions or false otherwise.
If you are concerned about the "unterminated character class" case, removing all non-alphanumeric chars would be helpful:
searchstring = searchstring.replace(/[^a-zA-Z 0-9]+/g,'');
I like #CHR15TO's answer, unlike other answers I've seen on other similar questions, that answer actually shows how to properly escape a user provided search string (rather than saying it would be necessary without showing how).
However, it's still quite clunky, and possibly relatively slower. So why not have a specific solution to what is likely a common requirement for coders? (And why not include it in the ES6 API BTW?)
My answer [https://stackoverflow.com/a/38290557/887092] on a similar question enables the following:
var haystack = 'A. BAIL. Of. Hay.';
var needle = 'bail.';
var index = haystack.naturalIndexOf(needle);
I do this often and use a simple 5 line prototype that accepts varargs. It is fast and works everywhere.
myString.containsIgnoreCase('red','orange','yellow')
/**
* #param {...string} var_strings Strings to search for
* #return {boolean} true if ANY of the arguments is contained in the string
*/
String.prototype.containsIgnoreCase = function(var_strings) {
const thisLowerCase = this.toLowerCase()
for (let i = 0; i < arguments.length; i++) {
let needle = arguments[i]
if (thisLowerCase.indexOf(needle.toLowerCase()) >= 0) {
return true
}
}
return false
}
/**
* #param {...string} var_strings Strings to search for
* #return {boolean} true if ALL of the arguments are contained in the string
*/
String.prototype.containsAllIgnoreCase = function(var_strings) {
const thisLowerCase = this.toLowerCase()
for (let i = 0; i < arguments.length; i++) {
let needle = arguments[i]
if (thisLowerCase.indexOf(needle.toLowerCase()) === -1) {
return false
}
}
return true
}
// Unit test
let content = `
FIRST SECOND
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
FOO BAR
`
let data = [
'foo',
'Foo',
'foobar',
'barfoo',
'first',
'second'
]
let result
data.forEach(item => {
console.log('Searching for', item)
result = content.containsIgnoreCase(item)
console.log(result ? 'Found' : 'Not Found')
})
console.log('Searching for', 'x, y, foo')
result = content.containsIgnoreCase('x', 'y', 'foo');
console.log(result ? 'Found' : 'Not Found')
console.log('Searching for all', 'foo, bar, foobar')
result = content.containsAllIgnoreCase('foo', 'bar', 'foobar');
console.log(result ? 'Found' : 'Not Found')
console.log('Searching for all', 'foo, bar')
result = content.containsAllIgnoreCase('foo', 'bar');
console.log(result ? 'Found' : 'Not Found')
There are two ways for case insensitive comparison:
Convert strings to upper case and then compare them using the strict operator (===).
Pattern matching using string methods:
Use the "search" string method for case insensitive search.
<!doctype html>
<html>
<head>
<script>
// 1st way
var a = "apple";
var b = "APPLE";
if (a.toUpperCase() === b.toUpperCase()) {
alert("equal");
}
//2nd way
var a = " Null and void";
document.write(a.search(/null/i));
</script>
</head>
</html>
You can make everything lowercase:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= (string.toLowerCase()).search((searchstring.toLowerCase()));
alert(result);
I was trying for incase-sensitive string search and I tried
var result = string.toLowerCase().match(searchstring)
and also
var result= string.search(new RegExp(searchstring, "i"));
But I did some little modifications and that worked for me
var result = string.match(new RegExp(searchstring, "i"));
This is will either lowercase, uppercase or combination also
I noticed that if the user enters a string of text but leaves the input without selecting any of the autocomplete options no value is set in the hidden input, even if the string coincides with one in the array.
So, with help of the other answers I made this:
var $local_source = [{
value: 1,
label: "c++"
}, {
value: 2,
label: "java"
}, {
value: 3,
label: "php"
}, {
value: 4,
label: "coldfusion"
}, {
value: 5,
label: "javascript"
}, {
value: 6,
label: "asp"
}, {
value: 7,
label: "ruby"
}];
$('#search-fld').autocomplete({
source: $local_source,
select: function (event, ui) {
$("#search-fld").val(ui.item.label); // display the selected text
$("#search-fldID").val(ui.item.value); // save selected id to hidden input
return false;
},
change: function( event, ui ) {
var isInArray = false;
$local_source.forEach(function(element, index){
if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) {
isInArray = true;
$("#search-fld").val(element.label); // display the selected text
$("#search-fldID").val(element.value); // save selected id to hidden input
console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);
};
});
if(!isInArray){
$("#search-fld").val(''); // display the selected text
$( "#search-fldID" ).val( ui.item? ui.item.value : 0 );
}
}