Is there a better way to implement "string contains substring" in javascript? - javascript

I am looking for better options in Javascript to check if a string contains a substring. Substring can either be a text from an input field or database.
Sample:
var substring = "DVI to VGA" //some code to get text from input field or database
var string = "12 DVI To VGA adapter"
if(string.toLowerCase().indexOf(substring.toLowerCase()) != -1){
//any action after match
console.log("FOUND A MATCH")
}

I can't think of any, but you can encapsulate what you have in a function that is more concise and reusable:
function stringContainsSubstring(string, substring) {
return string.toLowerCase().indexOf(substring.toLowerCase()) != -1;
}

var contains = (string.toLowerCase()).includes(substring.toLowerCase());

not exactly a solution, but you can use it like:
if(~string.toLowerCase().indexOf(substring.toLowerCase()){...
looks a bit cleaner

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, ''))};
})

Simple Javascript If Statement Issue

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

Extract all email addresses from bulk text using jquery

I'm having the this text below:
sdabhikagathara#rediffmail.com, "assdsdf" <dsfassdfhsdfarkal#gmail.com>, "rodnsdfald ferdfnson" <rfernsdfson#gmail.com>, "Affdmdol Gondfgale" <gyfanamosl#gmail.com>, "truform techno" <pidfpinfg#truformdftechnoproducts.com>, "NiTsdfeSh ThIdfsKaRe" <nthfsskare#ysahoo.in>, "akasdfsh kasdfstla" <akashkatsdfsa#yahsdfsfoo.in>, "Bisdsdfamal Prakaasdsh" <bimsdaalprakash#live.com>,; "milisdfsfnd ansdfasdfnsftwar" <dfdmilifsd.ensfdfcogndfdfatia#gmail.com>
Here emails are seprated by , or ;.
I want to extract all emails present above and store them in array. Is there any easy way using regex to get all emails directly?
Here's how you can approach this:
HTML
<p id="emails"></p>
JavaScript
var text = 'sdabhikagathara#rediffmail.com, "assdsdf" <dsfassdfhsdfarkal#gmail.com>, "rodnsdfald ferdfnson" <rfernsdfson#gmal.com>, "Affdmdol Gondfgale" <gyfanamosl#gmail.com>, "truform techno" <pidfpinfg#truformdftechnoproducts.com>, "NiTsdfeSh ThIdfsKaRe" <nthfsskare#ysahoo.in>, "akasdfsh kasdfstla" <akashkatsdfsa#yahsdfsfoo.in>, "Bisdsdfamal Prakaasdsh" <bimsdaalprakash#live.com>,; "milisdfsfnd ansdfasdfnsftwar" <dfdmilifsd.ensfdfcogndfdfatia#gmail.com> datum eternus hello+11#gmail.com';
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._+-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emails").text(extractEmails(text).join('\n'));
Result
sdabhikagathara#rediffmail.com,dsfassdfhsdfarkal#gmail.com,rfernsdfson#gmal.com,gyfanamosl#gmail.com,pidfpinfg#truformdftechnoproducts.com,nthfsskare#ysahoo.in,akashkatsdfsa#yahsdfsfoo.in,bimsdaalprakash#live.com,dfdmilifsd.ensfdfcogndfdfatia#gmail.com,hello+11#gmail.com
Source: Extract email from bulk text (with Regular Expressions, JavaScript & jQuery)
Demo 1 Here
Demo 2 Here using jQuery's each iterator function
You can use this regex:
var re = /(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/g;
You can extract the e-mails like this:
('sdabhikagathara#rediffmail.com, "assdsdf" <dsfassdfhsdfarkal#gmail.com>, "rodnsdfald ferdfnson" <rfernsdfson#gmail.com>, "Affdmdol Gondfgale" <gyfanamosl#gmail.com>, "truform techno" <pidfpinfg#truformdftechnoproducts.com>, "NiTsdfeSh ThIdfsKaRe" <nthfsskare#ysahoo.in>, "akasdfsh kasdfstla" <akashkatsdfsa#yahsdfsfoo.in>, "Bisdsdfamal Prakaasdsh" <bimsdaalprakash#live.com>,; "milisdfsfnd ansdfasdfnsftwar" <dfdmilifsd.ensfdfcogndfdfatia#gmail.com>').match(re);
//["sdabhikagathara#rediffmail.com", "dsfassdfhsdfarkal#gmail.com", "rfernsdfson#gmail.com", "gyfanamosl#gmail.com", "pidfpinfg#truformdftechnoproducts.com", "nthfsskare#ysahoo.in", "akashkatsdfsa#yahsdfsfoo.in", "bimsdaalprakash#live.com", "dfdmilifsd.ensfdfcogndfdfatia#gmail.com"]
Just an update to the accepted answer. This does not work for "plus" signs in the email address. GMAIL supports emailaddress+randomtext#gmail.com.
I've updated to:
return text.match(/([a-zA-Z0-9._+-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
The bellow function is RFC2822 compliant according to Regexr.com
ES5 :
var extract = function(value) {
var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
return value && value.match(reg);
}
ES6 :
const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
const extract = value => value && value.match(reg)
Regexr community source
function GetEmailsFromString(input) {
var ret = [];
var email = /\"([^\"]+)\"\s+\<([^\>]+)\>/g
var match;
while (match = email.exec(input))
ret.push({'name':match[1], 'email':match[2]})
return ret;
}
var str = '"Name one" <foo#domain.com>, ..., "And so on" <andsoon#gmx.net>'
var emails = GetEmailsFromString(str)
Source
You don't need jQuery for that; JavaScript itself supports regexes built-in.
Have a look at Regular Expression for more info on using regex with JavaScript.
Other than that, I think you'll find the exact answer to your question somewhere else on Stack Overflow - How to find out emails and names out of a string in javascript
const = regex = /\S+[a-z0-9]#[a-z0-9\.]+/img
"hello sean#example.com how are you? do you know bob#example.com?".match(regex)
A bunch of the answer in here are including lower/capital letters [a-zA-Z] AND the insensitive regex flag i, which is nonsense.
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z]).
\d matches a digit (equivalent to [0-9])As domain extensions don't end with numeric characters).
As a result, combined with the \d token. we get a much more condenses and elegant sentence.
/[a-z\d._+-]+#[a-z\d._-]+/gi
Demo
let input = 'sdabhikagathara#rediffmail.com, "assdsdf" <dsfassdfhsdfarkal#gmail.com>, "rodnsdfald ferdfnson" <rfernsdfson#gmail.com>, "Affdmdol Gondfgale" <gyfanamosl#gmail.com>, "truform techno" <pidfpinfg#truformdftechnoproducts.com>, "NiTsdfeSh ThIdfsKaRe" <nthfsskare#ysahoo.in>, "akasdfsh kasdfstla" <akashkatsdfsa#yahsdfsfoo.in>, "Bisdsdfamal Prakaasdsh" <bimsdaalprakash#live.com>,; "milisdfsfnd ansdfasdfnsftwar" <dfdmilifsd.ensfdfcogndfdfatia#gmail.com>'
function get_email(string) {
return string.match(/[a-z\d._+-]+#[a-z\d._-]+/gi)
};
$('#output').html(get_email(input).join('; '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>
See it live # https://regex101.com/r/OveC5B/1/

javascript get string before a character

I have a string that and I am trying to extract the characters before the quote.
Example is extract the 14 from 14' - €14.99
I am using the follwing code to acheive this.
$menuItem.text().match(/[^']*/)[0]
My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.
What I am I doing wrong with the match?
This is the what you should use to split:
string.slice(0, string.indexOf("'"));
And then to handle your non existant value edge case:
function split(str) {
var i = str.indexOf("'");
if(i > 0)
return str.slice(0, i);
else
return "";
}
Demo on JsFiddle
Nobody seems to have presented what seems to me as the safest and most obvious option that covers each of the cases the OP asked about so I thought I'd offer this:
function getCharsBefore(str, chr) {
var index = str.indexOf(chr);
if (index != -1) {
return(str.substring(0, index));
}
return("");
}
try this
str.substring(0,str.indexOf("'"));
Here is an underscore mixin in coffescript
_.mixin
substrBefore : ->
[char, str] = arguments
return "" unless char?
fn = (s)-> s.substr(0,s.indexOf(char)+1)
return fn(str) if str?
fn
or if you prefer raw javascript : http://jsfiddle.net/snrobot/XsuQd/
You can use this to build a partial like:
var beforeQuote = _.substrBefore("'");
var hasQuote = beforeQuote("14' - €0.88"); // hasQuote = "14'"
var noQoute = beforeQuote("14 €0.88"); // noQuote = ""
Or just call it directly with your string
var beforeQuote = _.substrBefore("'", "14' - €0.88"); // beforeQuote = "14'"
I purposely chose to leave the search character in the results to match its complement mixin substrAfter (here is a demo: http://jsfiddle.net/snrobot/SEAZr/ ). The later mixin was written as a utility to parse url queries. In some cases I am just using location.search which returns a string with the leading ?.
I use "split":
let string = "one-two-three";
let um = string.split('-')[0];
let dois = string.split('-')[1];
let tres = string.split('-')[2];
document.write(tres) //three

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 :/

Categories

Resources