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 :/
Related
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, ''))};
})
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
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
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
I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.
match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?
Use regex.test() if all you want is a boolean result:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
...and you could remove the () from your regexp since you've no need for a capture.
Use test() method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
You can use match() as well:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
But test() seems to be faster as you can read here.
Important difference between match() and test():
match() works only with strings, but test() works also with integers.
12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345); // true
/^([a-z0-9]{5,})$/.test(null); // false
// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true
Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
Remember to indicate ^ for beginning of the string and $ for the end, if you want to test the exact match of entire string.
Example:
/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
try
/^[a-z\d]{5,}$/.test(str)
console.log( /^[a-z\d]{5,}$/.test("abc123") );
console.log( /^[a-z\d]{5,}$/.test("ab12") );
I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.
let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null
let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
You can try this, it works for me.
<input type="text" onchange="CheckValidAmount(this.value)" name="amount" required>
<script type="text/javascript">
function CheckValidAmount(amount) {
var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
if(amount.match(a)){
alert("matches");
}else{
alert("does not match");
}
}
</script>
please try this flower:
/^[a-z0-9\_\.\-]{2,20}\#[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc#abc.abc');
true
If you don't want ^ and $ around the regex (I had such a usecase) you can do something like
let reg = /[a-zA-Z0-9]+/g
let txt = "hello"
let matches = reg.exec(txt)[0] == txt
console.log(`It ${matches ? "does" : "doesn't"} match`)
Update/Add
If the query string does not present in the URL then the below solution will work to add the param in the URL, if it already exists then it will update.
function updateUrlParameter(url, param, value) {
var regex = new RegExp("(?<=[?|&])(" + param + "=)[^&]+", "i");
if (regex.test(url)) {
return url.replace(regex, param + "=" + value);
} else {
if (window.location.search) {
return `${url}&${param}=${value}`;
}else{
return `${url}?${param}=${value}`;
}
}
}