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
Related
I don't want to allow special characters but this regular expression still allows them, what am I doing wrong?
When i type for name : '&é"é&'é"&'&é"'a' It still gives back 'true'
name.match(/[a-zA-Z1-9 ]/))
You need to use RegExp#test with anchors ^ and $.
/^[a-zA-Z1-9 ]+$/.test(name)
String#match return an array if match is found. In your case, a at the end of the string is found and array is returned. And array is truthy in the Javascript. I believe, the array is converted to Boolean, so it returned true.
It returns true because the last character ('a') is ok. Your regex doesn't check whether the complete input matches the regex.
Try this one:
^[a-zA-Z1-9 ]*$
if(!/[^a-zA-Z0-9]/.test(name)) {
// "your validation message"
}
try this
This will work for you:
var nameregex = /^([A-Za-z0-9 ]$)/;
var name = document.getElementById('name').value;
if (!name.match(nameregex)) {
alert('Enter Valid Name!!');
}
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_")
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.
Say we have a string
blue|blue|green|blue|blue|yellow|yellow|blue|yellow|yellow|
And we want to figure out whether the word "yellow" occurs in the last 5 words of the string, specifically by returning a capture group containing these occurences if any.
Is there a way to do that with a regex?
Update: I'm feeding a regex engine some rules. For various reasons I'm trying to work with the engine rather than go outside it, which would be my last resort.
/\b(yellow)\|(?=(?:\w+\|){0,4}$)/g
This will return one hit for each yellow| that's followed by fewer than five words (per your definition of "word"). This assumes the sequence always ends with a pipe; if that's not the case, you might want to change it to:
/\b(yellow)(?=(?:\|\w+){0,4}\|?$)/g
EDIT (in response to comment): The definition of a "word" in this solution is arbitrary, and doesn't really correspond to real-world usage. To allow for hyphenated words like "real-world" you could use this:
/\b(yellow)\|(?=(?:\w+(?:-\w+)*\|){0,4}$)/g
...or, for this particular job, you could define a word as one or more of any characters except pipes:
/\b(yellow)\|(?=(?:[^|]+\|){0,4}$)/g
No need to use a Regex for such a simple thing.
Simply split on the pipe, and check with indexOf:
var group = 'blue|blue|green|blue|blue|yellow|yellow|blue|yellow|yellow';
if ( group.split('|').slice(-5).indexOf('yellow') == -1 ) {
alert('Not there :(');
} else {
alert('Found!!!');
}
Note: indexOf is not natively supported in IE < 9, but support for it can be added very easily.
Can't think of a way to do this with a single regular expression, but you can form one for each of the last five positions and sum the matches.
var string = "blue|blue|green|blue|blue|yellow|yellow|blue|yellow|yellow|";
var regexes = [];
regexes.push(/(yellow)\|[^|]+\|[^|]+\|[^|]+\|[^|]+\|$/);
regexes.push(/(yellow)\|[^|]+\|[^|]+\|[^|]+\|$/);
regexes.push(/(yellow)\|[^|]+\|[^|]+\|$/);
regexes.push(/(yellow)\|[^|]+\|$/);
regexes.push(/(yellow)\|$/);
var count = 0;
var regex;
while (regex = regexes.shift()) {
if (string.match(regex)) {
count++;
}
}
console.log(count);
Should find four matches.
I have a javascript function that looks element id with certain patterns. So I have the following script:
if (f.elements[i].id.match(/DataList\[-\d{3}|\d{3}\]\.MemberId/)) {
//do something
}
It should match elements with ids such as these:
DataList[-1].MemberId
DataList[-2].MemberId
And it does, however it also matches the following:
DataList[-1].FirstName
DataList[-2].FirstName
which I don't want.
Could any guru take a look at the regular expression above and point out what is going wrong?
Thanks,
Cullen
Try to anchor your regex at the beginning with a ^ and at the end with a $, group your digit match and allow 1-3 digits instead of just 3.
if (f.elements[i].id.match(/^DataList\[(-\d{1,3}|\d{1,3})\]\.MemberId$/)) {
//do something
}
The way you had it, it was matching anything containing "DataList[-123" or containing "123].MemberId".
A simpler overall regex that accomplishes the same thing is:
if (f.elements[i].id.match(/^DataList\[-?\d{1,3}\]\.MemberId$/)) {
//do something
}
The or is saying:
DataList\[-\d{3} OR \d{3}\]\.MemberId/
This regex matches correctly:
DataList\[-?\d{1,3}\]\.MemberId
My suggestion
if (f.elements[i].id.match(/DataList\[-[0-9]{1,3}\]\.MemberId/)) {
}
The {} determines how many #s you want to support so 1-3 would match upu to [999]