entirely in JS, no server backend. I need to allow the user to search and then show a list of matched names. I'm using jQuery UI AutoComplete but need some JS to filter the results.
Given an Array of names:
Bob Hope
James Jones
Steve Jobs
Larry McBridge
Given a search term like Bo
How can I get just Bob Hope to return
Given a Search term like b:
How can I get all but James Jones?
Any simple JS for comparing two strings? Thanks
var names = ["Bob Hope","James Jones","Steve Jobs","Larry McBridge"]
var query = "bo"
var results = $(names)
.map(function(i,v){
if(v.toLowerCase().indexOf(query.toLowerCase())!=-1){return v}
}).get()
// results is ["Bob Hope"]
Maybe I misunderstood you (given the complexity of the above answer), but I came up with this which uses jQuery. Every time a key is pressed (when the input has focus), it searches all li elements on the page and finds whether they contain the search term.
Here is the HTML:
<ul><li>Bob Hope</li>
<li>James Jones</li>
<li>Steve Jobs</li>
<li>Larry McBridge</li></ul><br>
Search: <input id="search" length="24" />
And here is your jQuery:
$("#search").keyup(function(){
$("li").hide();
var term = $(this).val();
$("li:contains('" + term + "')").show();
});
Using Ivan's answer, but with ES6 changes:
var names = ["Bob Hope","James Jones","Steve Jobs","Larry McBridge"];
function findIn(s, list){
return list.filter((v) => v.toLowerCase().indexOf(s.toLowerCase()) != -1 );
}
findIn('bo', names);
Related
I have an array of email addresses that I obtained using .getViewers() from my sheet. This gives me the array of
[xxxxxjrhigh#xxxxxxx.org, /hd/domain/xxxxxxx.org, testemail3#googlemail.com, testemail2#gmail.com, testemail1#gmail.com]
Note: xxxxxxx replacing sensitive information
I am trying to remove the following from that array and then send an email to the remaining email addresses.
xxxxxjrhigh#xxxxxxx.org -and- /hd/domain/xxxxxxx.org
The index results always come back as -1 (no match found).
I'm new to coding so I'm sure it is an easy fix that I am just not aware of. I have tried putting my search term in 'single' quotes, in "double" quotes, and in no quotes at all. I tried assigning it to a variable and then using the variable in the indexOf(variable). I've watch 3 different tutorials on using indexOf() that do not indicate that I should have any trouble.
var viewers = SpreadsheetApp.getActiveSpreadsheet().getViewers();
Logger.log(viewers);
var index = viewers.indexOf('/hd/domain/xxxxxxx.org');
Logger.log(index);
viewers.splice( index, 1);
Logger.log(viewers);
var index = viewers.indexOf('xxxxxjrhigh#xxxxxxx.org');
Logger.log(index);
viewers.splice( index, 1);
Logger.log(viewers);
var string = ""+viewers;
Logger.log(string);
GmailApp.sendEmail(string, 'Test Treacker', 'This is the outcome from the test tracker');
Results I have been getting from the log:
index = -1.0
index = -1.0
string = xxxxxjrhigh#xxxxxxx.org,/hd/domain/xxxxxxx.org,testemail3#googlemail.com,testemail2#gmail.com
What I expect to get:
index = 0
index = 1
string = testemail3#googlemail.com,testemail2#gmail.com
You can take a look at what getViewers() call returns here: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet.html#getviewers. It is not an array of strings, but rather an array of User objects, each of which has a getEmail() method. The reason why your indexOf() returns a -1 for every email is that you are not working with an array of simple strings here!
To remove two users from the array based on their email you could do something like this:
const viewers = SpreadsheetApp.getActiveSpreadsheet().getViewers();
const filteredViewers = viewers.filter(viewer =>
viewer.getEmail() !== 'email1' && viewer.getEmail() !== 'email2');
Where email1 and email2 are emails of users you don't want to have in your resulting array.
Thank you #ajobi for pointing me in the right direction. While your code didn't help me because of the odd syntax error, your revelation that the items in my viewers array where accounts instead of actual email addresses got me thinking and doing a little more research. I stumbled on an answer that works for me.
I mapped the array of accounts to change it to an array of actual email addresses. This is what I came up with.
function correctEmails() {
var viewers = SpreadsheetApp.getActiveSpreadsheet().getViewers();
Logger.log(viewers);
var viewers1 = viewers.map(getEmails);
Logger.log(viewers1);
var index = viewers1.indexOf('/hd/domain/xxxxxxx.org');
Logger.log(index);
viewers1.splice( index, 1);
Logger.log(viewers1);
var index = viewers1.indexOf('xxxxxjrhigh#xxxxxxx.org');
Logger.log(index);
viewers1.splice( index, 1);
Logger.log(viewers1);
var string = ""+viewers1;
Logger.log(string+" - string");
// GmailApp.sendEmail(string, 'Test Treacker', 'This is the outcome from the test tracker');
//
}
function getEmails(item) {
return item.getEmail();
}
This results in the string I was looking for of testemail3#googlemail.com,testemail2#gmail.com and it will work no matter what order the email accounts are in.
Thanks!
Hello I am working on a project and last night I had a thought that would make a lot of what I am wanting to do a heck of a lot easier, the only problem is I am not sure on the best way to tackle it. Let me explain....
I have a form on a website where a user enters a VIP ID that is in a pre-determined format and follows a logical naming convention.
Example: app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
I want to pull out the following information from the entered text.
prod.platform.org.
Then I want to reverse it logically
.org.platform.prod
And then I want to replace the “.” For “/”
/org/platform/prod
And finally I want to add a postfix of “/open*”
/org/platform/prod/open*
So in short,
INPUT = app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
OUTPUT = /org/platform/prod/open*
I am using javascript/jquery for everything else but I am pretty new to all of this so I tend not to know the best route to tackle a problem. If I need to provide some more detail I can do. Any help is much appreciated.
Or simple like this
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb" ;
var output =
"/" +
input
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
var output =
"/" +
"app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb"
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
You can try below code :
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb";
var tempArr = input.split(".");
var newArr = new Array();
for(var i=1;i<tempArr.length;i++){
if(tempArr[i]=="org" || tempArr[i]=="net"){
newArr.push(tempArr[i]);
break;
}
newArr.push(tempArr[i]);
}
newArr.reverse();
var output="/"+newArr.join("/")+"/open*";
I'm making my own dropdown script in jQuery. Things are going well, but I'm running into a problem. Whenever I enter any characters into the text field, all elements in the array I am searching are displayed, instead of the elements that match what's in the textbox.
For example, if I regex search for "ra" against my array of:
var planes = [
'Alara',
'Fiora',
'Innistrad',
'Kamigawa',
'Lorwyn',
'Mirrodin',
'Ravnica',
'Shandalar',
'Zendikar'
];
I should only see Alara, Fiora, Innistrad and Ravnica in the autocomplete.
Here's a Plunker.
Any help is greatly appreciated.
You need to compare to -1, so it will only show if it is found. You are currently comparing to 1 instead, so it returns true for all items. Probably a typo. Good luck!
else{
//Grep used to search array but not alter the original.
var results = $.grep(planes, function(item){
return item.search(new RegExp(query, "i")) != *add a - here* 1;
});
console.log("Added " + query + " to cache.");
cache[query] = results;
}
I want to try and detect the different parts of a person's name in Javascript, and cut them out so that I can pass them onto something else.
Names can appear in any format - for example:-
miss victoria m j laing
Miss Victoria C J Long
Bob Smith
Fred
Mr Davis
I want to try and write something simple, that'll do it's best to guess these and get them right 80% of the time or so (We have some extremely dodgy data)
I'm thinking of something along the lines of using a regex to check whether it has a prefix, then branch off to two places as to whether it has
/^(Dr|Mr|Mrs|Miss|Master|etc).? /
And then cutting the rest of it out using something like
/(\w+ )+(\w+)/
To match last name and other names. Though, I'm unsure on my greedy/ungreedy options here, and whether I can do soemthing to shortcut having all the different paths that might be available. Basically, hoping to find something simple, that does the job in a nice way.
It's also got to be written in Javascript, due to the limitations of the ETL tool I'm using.
Why not split() and just check the resulting parts:
// Split on each space character
var name = "Miss Victoria C J Long".split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master|etc)\.?$/.test(name[0])) {
name.shift();
}
// Now you can access each part of the name as an array
console.log(name);
//-> Victoria,C,J,Long
Working Demo: http://jsfiddle.net/AndyE/p9ra4/
Of course, this won't work around those other issues people have mentioned in the comments, but you'd struggle on those issues even more with a single regex.
var title = '';
var first_name = '';
var last_name = '';
var has_title = false;
if (name != null)
{
var new_name = name.split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master)\.?$/i.test(new_name[0]))
{
title = new_name.shift();
has_title = true;
}
if (new_name.length > 1)
{
last_name = new_name.pop();
first_name = new_name.join(" ");
}
else if(has_title)
{
last_name = new_name.pop();
}
else
{
first_name = new_name.pop();
}
}
Adapted from Accepted Answer :)
I've been looking around on how to use JavaScript to set names to proper case, e.g. george mchall would become George McHall. I was able to find a write up on Codeproject on how to do this, as well as a person that intended it to do this:
function toProperCase(s){
return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
function($1, $2, $3, $4, $5) {
if($2){
return $3.toUpperCase()+$4+$5.toUpperCase();
}
return $1.toUpperCase();
});
}
This allows for what I'm looking for. But I need to be able to extend it further and add additional cases.
I found another page on John Gruber's site doing title case, but I'm only looking at doing names.
So, does anyone have an idea on extending it? I'm really just looking for a point in the right direction.
Edit:
Since I seem to be hitting a wall here, maybe someone has a way to do it server side. This is at least for now using ColdFusion for the server side. I've seen a C# implementation, but I'm not able to move to C# at the moment.
Combining a few answers from similar posts:
var selElem = document.getElementById("fromName");
selElem.addEventListener("change", function() {
document.getElementById("result").innerHTML = properName(selElem.value);
});
function properName(name) {
return ("" + name.replace(/[^\s\-\']+[\s\-\']*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
}).replace(/\b(Van|De|Der|Da|Von)\b/g, function(nobiliaryParticle) {
return nobiliaryParticle.toLowerCase();
}).replace(/Mc(.)/g, function(match, letter3) {
return 'Mc' + letter3.toUpperCase();
}));
}
<p>
Choose a name to see it properly capitalised:
</p>
<select id="fromName">
<option>Select a name</option>
<option>EMMA HURST</option>
<option>CHRIS HINDI</option>
<option>OSCAR GRENFELL</option>
<option>JIM CASEY</option>
<option>MEOW-LUDO DISCO GAMMA MEOW-MEOW</option>
<option>PAT SHEIL</option>
<option>NOEL MCFARLANE</option>
<option>CHRIS MCLACHLAN</option>
<option>ANTHONY ALBANESE</option>
<option>DAVID VAN GOGH</option>
<option>JAMIE ELVY</option>
</select>
<p>Result: <span id="result"></span></p>
How about this:
if (str==str.toLowerCase() || str==str.toUpperCase())
str = str.toTitleCase();
Otherwise, leave it well alone!!!
Edit: You could optionally split the string to weed out people holding the shift key for too long, like SMith.