Simple Javascript If Statement Issue - javascript

var sentence = prompt('Enter Sentence Here: ')
if(sentence === 'Billy'){
console.log('Great!');
}
I was wondering if there is a way to return "Great!' if the sentence isn't just "Billy" For Example how could you return "Great!" if the sentence was "My name is Billy" so what what I'm asking for is how to I get the if statement to scan the sentence and determine if that word is present then return what I wish.
My apologies for the simplicity and stupidity, this is my first day learning JS.

You should use regular expressions, searching for Billy:
/billy/i.test("I am Billy")

Use indexOf as follows:
if (sentence.toLowerCase().indexOf("billy") !== -1) {
All lower case is an additional laxing of the condition.
This is your full code:
var sentence;
sentence = prompt("Enter Sentence Here: ");
if (sentence.toLowerCase().indexOf("billy") !== -1)
{
console.log("Great!");
}

You can use .includes or .indexOf which scan a string for a substring.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
includes takes a string to search for and returns true if it finds it, otherwise false.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
indexOf takes a string to search for and if it finds it, will return the starting index of that string, so 'hello'.indexOf('ello') => 1 If it doesn't find it, it returns -1;
.includes
var sentence = prompt('Enter Sentence Here: ');
if (sentence.includes('Billy')) {
console.log('Great!');
}
.indexOf
var sentence = prompt('Enter Sentence Here: ');
if (sentence.indexOf('Billy') > -1) {
console.log('Great!');
}
Something to note is that it is case sensitive, so make sure you are typing 'Billy'. You can make use of toLowerCase and search for billy as well, and that way it would be case insensitive.

Regular expression
/billy/i.test("I am Billy");
es6 includes
"I am Billy".toLowerCase().includes("billy");
es6 contains
"I am Billy".toLowerCase().contains("billy");
old indexOf
"I am Billy".toLowerCase().indexOf("billy") !== -1;

<script>
if(prompt('Enter Sentence Here: ').toLowerCase().indexOf("billy") >= 0)
{
console.log('Great!');
}
</script>

you can use indexOf
var sentence = prompt('Enter Sentence Here: ');//"My name is Billy"
if(sentence.indexOf("Billy") !== -1){
console.log('Great!');
}
Incase you want case insensitive , you can use toLower() on string and then search for "billy"
if(sentence.toLowerCase().indexOf("billy") !== -1){
console.log('Great!');
}
Using regex is also one of the good options.
if(/billy/i.test(sentence)){
console.log('Great!');
}
Thanks for reading,

You can also use includes like:
if( sentence.includes('Billy') )
Check Browser support

Related

Search for one or more characters and replace in JavaScript

By using indexOf() I was able to detect if the input contains "SP-" and replace.
However, I need to look for more than one set of characters:
sp-, SP-, eb-, EB- and more...
I have the following to replace sp- and SP- but I don't want to replicate this entire block for every instance.
// Check for 'sp-' characters in the order ID.
if (order_id.indexOf("SP-") !== -1) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace("SP-", ""));
}
// Check for 'SP-' characters in the order ID.
if (order_id.indexOf("sp-") !== -1) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace("sp-", ""));
}
Update - Just thought of a better solution, find all characters before and including - and remove it. So we're not limited to a specific list in case new prefixes are added at a later date.
sp-1234, SP-1234, xx-1234, etc.
To replace all case insensitive can you try this
form.find('input[name="orderid"]').val(order_id.replace(/sp-/gi, ''));
or you can do something like this
['SP-', 'sp-', 'eb-', 'EB-'].forEach((item)=>{
if ( order_id.indexOf(item) !== -1 ) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace(item, ''));
}
});
Update - Just thought of a better solution, find all characters before
and including - and remove it. So we're not limited to a specific list
in case new prefixes are added at a later date.
sp-1234, SP-1234, xx-1234, etc.
Maybe something like this should work
if(order_id.indexOf('-') !== -1) {
var prefix = order_id.substr(0, order_id.indexOf('-'));
form.find('input[name="orderid"]').val(order_id.replace(`${prefix}-`, ""));
}
Just use a regular expression with case insensitivity set. There is no reason to check for the string exists inside the string because the replace method does not do anything if there is no match.
function removePrefix(str) {
return str.replace(/(sp|eb)-/i, '');
}
["fo-foooo", "sp-123", "SP-123", "eb-321", "EB-911"].forEach( function (str) {
console.log(str, removePrefix(str));
});
Matching anything that starts with a string followed by a dash
function removePrefix(str) {
return str.replace(/^[^-]+-/i, '');
}
["fo-foooo", "sp-123", "SP-123", "eb-321", "EB-911"].forEach( function (str) {
console.log(str, removePrefix(str));
});
Try something like this:
var vals = ["sp-","ep-"] // Put all the values here
vals.forEach(v => {
if (order_id.indexOf(v) !== -1) {form.find('input[name="orderid"]').val(order_id.replace(v, ''))};
})

JavaScript-Creating a Function to capitalise the first letter of a string [duplicate]

This question already has answers here:
Convert string to Pascal Case (aka UpperCamelCase) in Javascript
(5 answers)
Closed 2 years ago.
I'm having trouble in creating a function to capitalise the first letter of a string. I can capitalise the string when I enter words in lowercase, but not in uppercase. I really appreciate some assistance with this problem, please see my script below:
function captialise(str) {
str = prompt("Enter a string");
console.log(str[0].toUpperCase() + str.substring(1))
}
captialise();
Uppercase the first character, lowercase the rest. The snippet uses a bit more modern scripting (the function uses a template literal)
const capitalize = str => str.slice
? `${str.slice(0,1).toUpperCase()}${str.slice(1).toLowerCase()}`
: str;
const str1 = `someSTRING`;
const str2 = `someotherstring`;
const str3 = `s23omeotherstring`;
const str4 = prompt('enter something');
console.log(capitalize(str1));
console.log(capitalize(str2));
console.log(capitalize(str3));
console.log(capitalize(str4));
There are many ways to do it, and I believe it was asked a lot of time here before,
This one is with one line:
function captialise(str) {
str = prompt("Enter a string");
console.log(`${str[0].toUpperCase()}${str.substring(1).toLowerCase()}`);
}
captialise();
The logical problem is that you're capitalising the first part yes, but you're NOT lowering the other parts
function captialise(str) {
str = prompt("Enter a string");
console.log(str[0].toUpperCase() + str.substring(1).toLowerCase())
}
captialise();
It is recommended to have a function return what you name it.
You need to lowerCase the rest of the string too and I would test you have a string in the first place
I chose to use + instead of template literals since it is easier to read in this simple case
const captialise = str => str && typeof str === "string" ?
str.slice(0,1).toUpperCase() + str.slice(1).toLowerCase() :
str;
console.log(
captialise(prompt("Enter a string"))
)

How to check if a string contains a WORD in javascript? [duplicate]

This question already has answers here:
How to check if a string contain specific words?
(11 answers)
Closed 3 years ago.
So, you can easily check if a string contains a particular substring using the .includes() method.
I'm interested in finding if a string contains a word.
For example, if I apply a search for "on" for the string, "phones are good", it should return false. And, it should return true for "keep it on the table".
You first need to convert it into array using split() and then use includes()
string.split(" ").includes("on")
Just need to pass whitespace " " to split() to get all words
This is called a regex - regular expression
You can use of 101regex website when you need to work around them (it helps). Words with custom separators aswell.
function checkWord(word, str) {
const allowedSeparator = '\\\s,;"\'|';
const regex = new RegExp(
`(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,
// Case insensitive
'i',
);
return regex.test(str);
}
[
'phones are good',
'keep it on the table',
'on',
'keep iton the table',
'keep it on',
'on the table',
'the,table,is,on,the,desk',
'the,table,is,on|the,desk',
'the,table,is|the,desk',
].forEach((x) => {
console.log(`Check: ${x} : ${checkWord('on', x)}`);
});
Explaination :
I am creating here multiple capturing groups for each possibily :
(^.*\son$) on is the last word
(^on\s.*) on is the first word
(^on$) on is the only word
(^.*\son\s.*$) on is an in-between word
\s means a space or a new line
const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;
console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));
You can .split() your string by spaces (\s+) into an array, and then use .includes() to check if the array of strings has your word within it:
const hasWord = (str, word) =>
str.split(/\s+/).includes(word);
console.log(hasWord("phones are good", "on"));
console.log(hasWord("keep it on the table", "on"));
If you are worried about punctuation, you can remove it first using .replace() (as shown in this answer) and then split():
const hasWord = (str, word) =>
str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/).includes(word);
console.log(hasWord("phones are good son!", "on"));
console.log(hasWord("keep it on, the table", "on"));
You can split and then try to find:
const str = 'keep it on the table';
const res = str.split(/[\s,\?\,\.!]+/).some(f=> f === 'on');
console.log(res);
In addition, some method is very efficient as it will return true if any predicate is true.
You can use .includes() and check for the word. To make sure it is a word and not part of another word, verify that the place you found it in is followed by a space, comma, period, etc and also has one of those before it.
A simple version could just be splitting on the whitespace and looking through the resulting array for the word:
"phones are good".split(" ").find(word => word === "on") // undefined
"keep it on the table".split(" ").find(word => word === "on") // "on"
This just splits by whitespace though, when you need parse text (depending on your input) you'll encounter more word delimiters than whitespace. In that case you could use a regex to account for these characters.
Something like:
"Phones are good, aren't they? They are. Yes!".split(/[\s,\?\,\.!]+/)
I would go with the following assumptions:
Words the start of a sentence always have a trailing space.
Words at the end of a sentence always have a preceding space.
Words in the middle of a sentence always have a trailing and preceding space.
Therefore, I would write my code as follows:
function containsWord(word, sentence) {
return (
sentence.startsWith(word.trim() + " ") ||
sentence.endsWith(" " + word.trim()) ||
sentence.includes(" " + word.trim() + " "));
}
console.log(containsWord("test", "This is a test of the containsWord function."));
Try the following -
var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
console.log('Substring found !!')
} else {
console.log('Substring not found !!')
}

Determining whether a string has a substring (word)

I try to use a conditional to verify if a string contain a certain word, for example:
I want to use a method (regex?) to find if a string has the text "&SWE>clickable".
var text1 = "layer_legs";
var text2 = "layer_head&SWE>clickable";
if (....)
document.write ("the layer is clickable")
else
document.write ("the layer is not clickable")
How can I do that?
You can use String.indexOf. It returns -1 if the string is not found, otherwise it returns the index where the string was found. You can use it like this:
if (s.indexOf("&SWE>clickable") !== -1) { ... }
if (text2.indexOf("&SWE>clickable") > -1) {
....
try this :
if (text1.indexOf('&SWE>clickable')>=0){ ... }
or regex way :
var re = new RegExp('\&SWE\>clickable')
if (re.test(text1)){ ... }
if(text1.indexOf(text2))
document.write ("the layer is clickable")
else
document.write ("the layer is not clickable")
if (/&SWE>clickable/g.test(text2)) {
// exists
}
EDIT: Using indexOf like others have posted might be better, since it’s more readable and you don‘t need to escape characters. And arguably faster :/

Javascript Match on parentheses inside the string

How do I do a .match on a string that has parentheses in the string?
String1.match("How do I match this (MATCH ME)");
None of the answers are getting me what I want. I'm probably just doing it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:
$('[id$=txtEntry3]').focus(function () {
if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
ErrorMessageIn("The Ingredient number you entered is not valid.");
return;
}
ErrorMessageOut();
});
This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.
Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:
$('[id$=txtEntry3]').focus(function () {
if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
if (!$('[id$=txtEntry2]').val() == "") {
ErrorMessageIn("The Ingredient number you entered is not valid.");
}
return;
}
ErrorMessageOut();
});
function StripParentheses(String){
x = String.toString().replace(/\(/g, '');
x = x.toString().replace(/\)/g, '');
return x;
}
to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag
string.match(/\((.*?)\)/g)
this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)
If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);

Categories

Resources