Javascript - search a string from beginning - javascript

Hello i currently have this part of the code that i developed but i want to do some edits:
$('#target').keydown(function(event) {
if (event.which == 13)
{
var users = ["Dennis Lucky","Lucy Foo","Name Lastname","Billy Jean"];
var match = 0;
var str = $('#target').val();
for(i=0;i<users.length;i++)
{
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
{
match++;
name = users[i];
}
}
if(match == 1)
{
$('#target').val('');
$('#chatbox').append('<span style="color:blue;">'+name+'</span> ');
console.log(name);
}
else if (match >= 2)
{
console.log("many entries");
}
}});
The idea is that if i type something and hit enter if the partial string exists in users becomes blue color.With this code i have the problem that if i write "Lu" i get 2 results, "Dennis Lucky" and "Lucy Foo".
I want to change my code so when i type "Lu" it will start searching the words starting with this sting and not include it.

if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
The condition is true if indexOf's returned value is greater than -1. In JavaScript, indexOf returns -1 if a match "needle" (the string you're searching for) isn't found in your "haystack" (the string that you're searching within). Otherwise, it returns the first index of the "needle" in your "haystack".
To explain my terminology of indexOf, here's an example:
haystack.indexOf(needle); // How to use the indexOf function
console.log("apples oranges apples".indexOf("apples")); // This would print 0.
console.log("apples oranges apples".indexOf("white")); // This would print -1.
If you want to ensure that the string starts with the "needle", you simply need to change your code to
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) == 0 )
If you want your "words" ("Lucy Foo" would be "Lucy" and "Foo"), either split your name strings by a space character and perform the indexof search with the elements of the resultant array, or turn to regex.

It is better to use regexes. Since you want to search the start of string use ^
Refer Regular Expressions documentation on MDN for more information.

Related

Calculate the string length of only characters (not symbols) in the string using Javascript

I am trying to select words being passed through an IF statement based on only their character length, ignoring symbols.
For example If I have the word "hello!" I want the if statement to recognise it as a length of 5 characters.
I want to keep the symbol in the word when it is then added to updatedString. I just don't want to count the symbol in the original count. I have spent a while considering regex options but am struggling to find something that would work in this particular case.
An example of part of the code is below. (updatedString is declared outside of the if-loop)
for (let word in arr) {
if (arr[word].length == 5 || arr[word].length == 6) {
let bold = arr[word].slice(0, 3)
let normal = arr[word].slice(3)
updatedString += `<b>${bold}</b>${normal} `
}
else if {
...
}
}
What I ultimately want is the area "arr[word].length == 5" to only count characters.
For the sake of this program I will assume that all words input in via the user will be those used in normal news or academic articles and nothing too obscure.
Any advice would be greatly appreciated, thanks.
You can use regex like so:
text = "hello!"
text.match(/[a-z]/g).join("") // join to return a string without any symbols
If you need to match more characters just update the pattern.
In your particular case it would look something like this:
for (let word in arr) {
if (arr[word].match(/[a-z]/g).length == 5 || arr[word].match(/[a-z]/g).length == 6) {
let bold = arr[word].slice(0, 3)
let normal = arr[word].slice(3)
updatedString += `<b>${bold}</b>${normal} `
}else if (/* [...] */) {
// [...]
}
}

How do I check for brackets in a specific place in the string?

I have this code and it needs to returns true or false based on the string you give it.
This is the only example on which it doesn't work. How can I check if brackets exist in a specific index of the string?
function telephoneCheck(str) {
var newStr = str.replace(/-/g,'').replace(/ /g,'').replace(/\(|\)/g,'');
var valid = true;
var re = /\([^()]*\)/g;
while (str.match(re))
str = str.replace(re, '');
if (str.match(/[()]/)){
valid = false;
}
if(newStr.length === 10 && valid === true && str.indexOf()){
return true;
}else if(newStr.length === 11 && str[0] != "-" && newStr[0] == 1 && valid === true){
return true;
}else{
return false;
}
}
telephoneCheck("(6505552368)");
Based on your code I think you might be looking for something like this:
'(6505552368)'.replace(/^\((\d+)\)$/, '$1');
The ^ and $ in the RegExp will match the start and the end of the string. The \d+ will match one or more numbers. The extra parentheses form a capture group that is then used in the replacement as $1.
You might be better off doing more work using RegExps rather than doing all that replacing but without knowing the exact requirements it's difficult to be more precise. I highly suggest learning more about RegExp syntax.
If you literally just want to know whether 'brackets exist in a specific index' then you can just use:
str.charAt(index) === '(';
To check if there are brackets at a specific index in the string:
/[()]/.test(str[index])
To check if there are any brackets in the string at all:
/[()]/.test(str)
If you want to test for a specific bracket type (e.g. opening but not closing) remove the other one (e.g. closing) from the regex.

Accept any value in JavaScript? (Regular expression?)

I am creating a small very simple game.
I want to know how to accept any input value in the following code...
if(answer === "My name is" + * + "and I am a Leo" ) {
alert("Correct!")
}
To my understanding the asterisks would accept any value input by the user.
Besides that, script breaks after i write the above.
Forgot to add the JSFIddle
Try this:
if (answer.substring(0, 10) == "My name is" && answer.slice(-14) == "and I am a Leo") {
alert("Correct!");
}
substring(0, 10) -> gets the first 10 characters
slice(-14) -> gets the last 14 characters
Here's a regex approach too:
var matches = answer.match(/^My name is (.*) and I am a Leo$/);
if (matches != null) {
alert("Correct!"); //use matches[1] to get the name
}
I assume you have already prompted the user for a value to the answer variable.
You probobly want to use a regeular expression:
if (answer.search(/^My name is.*and I am a Leo$/) === 0) {
alert("Correct!");
}
Look at this cheatsheet to see what the difference characters mean. The search method returns the position of the match in the string, or -1 at failure. In this case, since ^ matches the start of the string, it will always return 0 on success.
$ matches the end of the string and .* means match any character except newline 0 or more times (that is any amount of times).

Javascript: multiple expressions in array when searching strings

I'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm looking for. I have a function here:
function findCertainWords()
{
var t = {Some text value};
if (t in {'one':'', 'two':''})
return alert("At least one string is found. Change them."), 0;
return 1
}
Variable a is user's written text (for example, a comment or a post).
I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.
It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.
Use indexOf to test if a string contains another string. Use .toLowerCase to convert it to one case before comparing.
function findCertainWords(t) {
var words = ['one', 'two'];
for (var i = 0; i < words.length; i++) {
if (t.toLowerCase().indexOf(words[i]) != -1) {
alert("At least one string was found. Change them.");
return false;
}
}
return true;
}
Another way is to turn the array into a regexp:
var regexp = new RegExp(words.join('|'));
if (regexp.test(t)) {
alert("At least one string was found. Change them.");
return false;
} else {
return true;
}
You can use Array.some with Object.keys
if(Object.keys(obj).some(function(k){
return ~a.indexOf(obj[k]);
})){
// do something
}

How to get portion of the attribute value using jquery

I have attribute value as:
<div id = "2fComponents-2fPromotion-2f" class = "promotion">
Now I want to get only portion of it, say Promotion and its value 2f, how can I get this using jquery ? Do we have built in function for it ?
You can use a regular expression here:
var attId = $(".promotion").attr("id");
// Perform a match on "Promotion-" followed by 2 characters in the range [0-9a-f]
var match = attId.match(/Promotion-([0-9a-f]{2})/);
alert(match[1]); // match[0] contains "Promotion-2f", match[1] contains "2f"
This assumes that the "value" of Promotion is a hexadecimal value and the characters [a-f] will always be lower case. It's also easily adjusted to match other values, for instance, if I change the regex to /component-([0-9a-f]{2})/, the match array would be ["component-3a", "3a"].
The match method takes a regular expression as its input and searches the string for the results. The result is returned as an array of matches, with the first index being the complete match (equivalent regex for this only would be /Promotion-[0-9a-f]{2}/). Any sub-expression (expressions enclosed in parenthesis) matches are added to the array in the order they appear in the expression, so the (Promotion) part of the expression is added to the array at index 1 and ([0-9a-f]{2}) is added at index 2.
match method on MSDN
var id = $("div.promotion").attr("id");
var index = id.indexOf("Promotion");
var promotion = '';
// if the word 'Promotion' is present
if(index !== -1) {
// extract it up to the end of the string
promotion = id.substring(index);
// split it at the hyphen '-', the second offset is the promotion code
alert(promotion.split('-')[1]);
} else {
alert("promotion code not found");
}
you can get the id attribute like this:
var id= $('div.promotion').attr('id');
But then I think you would have to use regular expressions to parse data from the string, the format doesn't appear to be straight forward.
If you are storing lots of info in the id could you consider using multiple attributes like:
<div class="promotion" zone="3a-2f-2f" home="2f"></div>
Then you could get the data like this:
var zone= $('div.promotion').attr('zone');
var home= $('div.promotion').attr('home');
Or you could use jQuery.data()
HTH
$(function () {
var promotion = $('.promotion').attr('id').match(/Promotion-([0-9a-f]{2})/);
if (promotion.length > 0) {
alert(promotion[1]);
}
else {
return false;
}
});

Categories