Determine Whether String Begins With Particular Letters - javascript

I am trying to determine using javascript and regex whether a string begins with certain letters. If it's true I want it do something. I am trying to find the value "window_" in a particular string.
My code is as follows:
if (div_type.match(/^\window_/)){
}
This however is returning true when it clearly doesn't contain it.

Regular expressions are overkill for this kind of string matching:
if (div_type.indexOf("window_") === 0) {
// Do something
}

If you really want to go the regex route, you can use test() instead of match() /regex_pattern/.test(string)
Example:
function run(p){
return /^window_/.test(p);
}
console.log(run("window_boo"), // true
run("findow_bar")); // false
Your use:
if ( /^window_/.test(div_type) ) {
...
}

You don't need a regex for that.
if( div_type.substr(0,"window_".length) == "window_")

Related

IndexOf Returning Partial Match

I am having an issue with a piece of javascript that's evaluating to true when I do not want it to do so. When indexOf evaluates rec.name - which equals "CSI" - it returns true and triggers the continue line because the finalArr array contains an element named "CSIQ Group". However, that's not what I want, as I only want it to evaluate to true if it finds an element in the array that is an exact match.
Here's the snippet of code:
if(finalArr.join().indexOf(rec.name.toString()) > -1){
continue;
}
What can I change to prevent "CSI" from triggering the continue line when "CSIQ Group" is already in finalArr? Thanks!
Kind Regards,
Joseph
You could try using findIndexOf or in your case just find should do the trick, or even includes.
Something like this:
if(finalArr.includes(rec.name){
continue;
}
includes is great for a simple string match. If you want greater matching then you can try find. find will let you compare each element in the array against a certain condition and you can perform multiple checks on it.
if(!!finalArr.find(element => (element.toLowerCase() === name.rec.toLowerCase()){
continue;
}
I would, however, definitely recommend against converting your array to a string and trying to search it, especially for this case.
You could use RegExp to match the string exactly to CSI:
const pattern = /^CSI$/ // ^ - start of the string, $ - end of the string
pattern.test(rec.name.toString()) // true if only "CSI", false otherwise
You could use this to amend your code and do what you need if word CSI is found.

How can I make javascript match the start of a string?

I have the following coce:
if (link.action === "Create") {
However my link.action could be:
Create xxxx
Is there a way I can change this match so it just checks for the start being "Create" ?
Just Check string.indexOf(string_to_check). It returns the index number for a 'string_to_check', if it exists in the string. Any in your case, you want the string start with "Create", so the index should be always 0 in your case.
So, You can try this
if (link.action.indexOf("Create") == 0) {
Use a regular expression.
if (link.action.match(/^Create/) {
}
^ is a special character: an anchor which matches only the beginning of the input.
More reading on regex in general: http://www.regular-expressions.info
link.action.slice(0,6)=="Create"
Will also work as you like as above mentioned methods. For further read String object reference in java script.

Javascript wildcard variable?

The value of product_id might be some combination of letters and numbers, like: GB47NTQQ.
I want to check to see if all but the 3rd and 4th characters are the same.
Something like:
if product_id = GBxxNTQQ //where x could be any number or letter.
//do things
else
//do other things
How can I accomplish this with JavaScript?
Use regular expression and string.match(). Periods are single wildcard characters.
string.match(/GB..NTQQ/);
Use a regular expression match:
if ('GB47NTQQ'.match(/^GB..NTQQ$/)) {
// yes, matches
}
Answers so far have suggested match, but test is likely more appropriate as it returns true or false, whereas match returns null or an array of matches so requires (implicit) type conversion of the result within the condition.
if (/GB..NTQQ/.test(product_id)) {
...
}
if (myString.match(/regex/)) { /*Success!*/ }
You can find more information here: http://www.regular-expressions.info/javascript.html

javascript check for a special character at the beginning a string

I am trying to get a value from input field.
I want to check if the string has % or * at the beginning of the string then show an alert.
if (/^[%*]/.test(document.getElementById("yourelementid").value))
alert("Where can I find a JavaScript tutorial?");
By way of explanation: the regular expression /^[%*]/ means:
^ match the beginning of the string, followed immediately by
[%*] any one of the characters inside the brackets
Testing the entered value against that regex will return true or false.
getElementById(ID).value.charAt(0);
I'm sure you can figure out the rest. Please do some research first as things like this should be really easy to find by googling it.
You can use the substring method, for example:
data.substring(0, 1) === '%'
if(data.substring(0, 1) === '%' || data.substring(0, 1) === '*')
{
alert("Not allowed");
}
or you can try the regex way.
You can do that by using the indexOf method of strings.
var s = "%kdjfkjdf";
if (s.indexOf("%") == 0 || s.indexOf("*") == 0)
{
// do something
}
You can also use regular expressions too as pointed out in #nnnnnn's answer.
Refer to below link.
javascript pattern matching
var str="%*hkfhkasdfjlkjasdfjkdas";
if(str.indexOf("%") === 0|| str.indexOf("*") === 0){
alert("true");
}
else{
alert("false");
}
please check fiddle here.
http://jsfiddle.net/RPxMS/
you can also use prototype plugin for javascript which contains method startWith.
if(str.startWith("%"))
{
// do
}
check the details in the link: click here

How do I use regex to perform a validation?

I'd like to evaluate a form field using a regex.
What expression do I use to actually compare the value to the regex?
I'm imagining something thus:
if($('#someID').val() == /someregex/) {doSomething()}
But that doesn't work. Any advice?
Use
if (/^someregex$/.test($('someID').value()) {
// match
} else {
// no match
}
Note that there is no value() method in jQuery, you need to use val() and match like this:
if($('#someID').val().match(/someregex/) {
// success
}
More Info:
http://www.regular-expressions.info/javascript.html
use the match method of the strings..
string.match(regexp)
so in your case
if( $('#someID').value().match(/someregex/) ) {doSomething()}
I think you're looking for .test():
var myRegex = /someregex/;
if ( myRegex.test($('#someID').value()) ) {
doSomething();
}
You can use exec() to check it and get an array of it's matches, or match() from the string object.
We don't compare values to regular expressions. We use regular expressions to test if a value matches a pattern.
Something like:
if (/myRegExp/.test($('#myID').val()) {
//... do whatever
}
see
http://www.evolt.org/regexp_in_javascript

Categories