This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 4 years ago.
I need a JS expression to match a combination of /* characters
I have this now
/(\b\/*\b)g
but it does not work.
ETA:
any string that has /* should match
so...
Hello NO MATCH
123 NO MATCH
/* HELLo MATCH
/*4534534 MATCH
Since you only want to detect if it contains something you don't have to use regex and can just use .includes("/*"):
function fits(str) {
return str.includes("/*");
}
var test = [
"Hello NO MATCH",
"123 NO MATCH",
"/* HELLo MATCH",
"/*4534534 MATCH"
];
var result = test.map(str => fits(str));
console.log(result);
You might use a positive lookahead and test if the string contains /*?
If so, match any character one or more times .+ from the beginning of the string ^ until the end of the string $
^(?=.*\/\*).+$
Explanation
^ Begin of the string
(?= Positive lookahead that asserts what is on the right
.*\/\* Match any character zero or more time and then /*
) Close positive lookahead
.+ Match any character one or more times
$ End of the string
const strings = [
"Hello NO MATCH",
"123 NO MATCH",
"/* HELLo MATCH",
"/*4534534 MATCH",
"test(((*/*"
];
let pattern = /^(?=.*\/\*).+$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});
I think you could also use indexOf() to get the index of the first occurence of /*. It will return -1 if the value is not found.
const strings = [
"Hello NO MATCH",
"123 NO MATCH",
"/* HELLo MATCH",
"/*4534534 MATCH",
"test(((*/*test",
"test /",
"test *",
"test /*",
"/*"
];
let pattern = /^(?=.*\/\*).+$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
console.log(s + " ==> " + (s.indexOf("/*") !== -1));
});
Related
I want to have a regular expression in JavaScript which help me to validate a string with contains only lower case character and and this character -.
I use this expression:
var regex = /^[a-z][-\s\.]$/
It doesn't work. Any idea?
Just use
/^[a-z-]+$/
Explanation
^ : Match from beginning string.
[a-z-] : Match all character between a-z and -.
[] : Only characters within brackets are allowed.
a-z : Match all character between a-z. Eg: p,s,t.
- : Match only strip (-) character.
+ : The shorthand of {1,}. It's means match 1 or more.
$: Match until the end of the string.
Example
const regex= /^[a-z-]+$/
console.log(regex.test("abc")) // true
console.log(regex.test("aBcD")) // false
console.log(regex.test("a-c")) // true
Try this:
var regex = /^[-a-z]+$/;
var regex = /^[-a-z]+$/;
var strs = [
"a",
"aB",
"abcd",
"abcde-",
"-",
"-----",
"a-b-c",
"a-D-c",
" "
];
strs.forEach(str=>console.log(str, regex.test(str)));
Try this
/^[a-z-]*$/
it should match the letters a-z or - as many times as possible.
What you regex does is trying to match a-z one single time, followed by any of -, whitespace or dot one single time. Then expect the string to end.
Use this regular expression:
let regex = /^[a-z\-]+$/;
Then:
regex.test("abcd") // true
regex.test("ab-d") // true
regex.test("ab3d") // false
regex.test("") // false
PS: If you want to allow empty string "" to pass, use /^[a-z\-]*$/. Theres an * instead of + at the end. See Regex Cheat Sheet: https://www.rexegg.com/regex-quickstart.html
I hope this helps
var str = 'asdadWW--asd';
console.log(str.match(/[a-z]|\-/g));
This will work:
var regex = /^[a-z|\-|\s]+$/ //For this regex make use of the 'or' | operator
str = 'test- ';
str.match(regex); //["test- ", index: 0, input: "test- ", groups: undefined]
str = 'testT- ' // string now contains an Uppercase Letter so it shouldn't match anymore
str.match(regex) //null
I have input strings I'm trying to validate.
I may have some delimiters between "abc 123" and "abcd 123", i.e possible scenarios:
str = "abc-123 abcd 123";
str = "abc/123 abcd 123";
str = "abc&&123 abcd 123";
str = "abc:123 abcd 123";
str = "abc.123 abcd 123";
etc.....
Basically I want to consider all these strings as valid inout string
My regex:
var m = value.match(/([a-z]+\s*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)/i);
if (m) {return "valid string"}
else {return "invalid string"}
Currently my regex throws "invalid string" for the above listed scenarios except for whitespaces
( str= "User 123") // return valid string
how can I add a condition in my regex to evaluate all the above scenarios to true?
function testIt(value) {
var m = value.match(/([a-z]+\s*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)/i);
if (m) {return "valid string"}
else {return "invalid string"}
}
console.log(testIt("abc-123 abcd 123"));
console.log(testIt("abc/123 abcd 123"));
console.log(testIt("abc&&123 abcd 123"));
console.log(testIt("abc:123 abcd 123"));
console.log(testIt("abc.123 abcd 123"));
Either put all possible characters into a character set between the [a-z]+ and the \d+:
([a-z]+[\s\/&:.-]*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)
^^^^^^^^^^^
https://regex101.com/r/HJg1cE/1
Or, repeat any non-digit characters until you get to a digit character (if indeed any non-digit character is permitted there):
([a-z]+\D*\d+)\s+([a-z]+\s*\d+|\d+\s*[a-z]+)
^^^
I need a regex that will match the following:
a.b.c
a0.b_.c
a.bca._cda.dca-fb
Notice that it can contain numbers, but the groups are separeted by dots. The characters allowed are a-zA-z, -, _, 0-9
The rule is that it cannot start with a number, and it cannot end with a dot. i.e, the regex should not match
0a.b.c
a.b.c.d.
I have come up with a regex, which seems to work on regex101, but not javascript
([a-zA-Z]+.?)((\w+).)*(\w+)
`
But does not seem to work in js:
var str = "a.b.c"
if (str.match("([a-zA-Z]+.?)((\w+).)*(\w+)")) {
console.log("match");
} else {
console.log("not match");
}
// says not match
Your regex matches your values if you use anchors to assert the start ^ and the end $ of the line.
As an alternative you might use:
^[a-z][\w-]*(?:\.[\w-]+)*$
This will assert the start of the line ^, matches a word character \w (which will match [a-zA-Z0-9_]) or a hyphen in a character class [\w-].
Then repeat the pattern that will match a dot and the allowed characters in the character class (?:\.[\w-]+)* until the end of the line $
const strings = [
"a.b.c",
"A.b.c",
"a0.b_.c",
"a.bca._cda.dca-fb",
"0a.b.c",
"a.b.c.d."
];
let pattern = /^[a-z][\w-]*(?:\.[\w-]+)*$/i;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});
If the match should not start with a digit but can start with an underscore or hypen you might use:
^[a-z_-][\w-]*(?:\.[\w-]+)*$
Use forward slashes / and paste the regex code between them from online regex testers, when you use JavaScipt.
Here are, what I've changed in your regex pattern:
added ^ at the beginning of your regex to match the beginning of the input
added $ at the end to match the end of the input
removed A-Z and added the i modifier for case-insensitive search (this is optional).
Also, when you use regex101, make sure to select JavaScript Flavor, when creating/testing your regex for JavaScript.
var pattern = /^([a-z]+.?)((\w+).)*(\w+)$/i;
// list of strings, that should be matched
var shouldMatch = [
'a.b.c',
'a0.b_.c',
'a.bca._cda.dca-fb'
];
// list of strings, that should not be matched
var shouldNotMatch = [
'0a.b.c',
'a.b.c.d.'
];
shouldMatch.forEach(function (string) {
if (string.match(pattern)) {
console.log('matched, as it should: "' + string + '"');
} else {
console.log('should\'ve matched, but it didn\'t: "' + string + '"');
}
});
shouldNotMatch.forEach(function (string) {
if (!string.match(pattern)) {
console.log('didn\'t match, as it should: "' + string + '"');
} else {
console.log('shouldn\'t have matched, but it did: "' + string + '"');
}
});
More on regexes in JavaScript
I'm struggling with a regex for Javascript.
Here is a string from which I want to match all words but the one prefixed by \+\s and suffixed by \s\+ :
this-is my + crappy + example
The regex should match :
this-is my + crappy + example
match 1: this-is
match 2: my
match 3: example
You can use the alternation operator in context placing what you want to exclude on the left, ( saying throw this away, it's garbage ) and place what you want to match in a capturing group on the right side.
\+[^+]+\+|([\w-]+)
Example:
var re = /\+[^+]+\+|([\w-]+)/g,
s = "this-is my + crappy + example",
match,
results = [];
while (match = re.exec(s)) {
results.push(match[1]);
}
console.log(results.filter(Boolean)) //=> [ 'this-is', 'my', 'example' ]
Alternatively, you could replace between the + characters and then match your words.
var s = 'this-is my + crappy + example',
r = s.replace(/\+[^+]*\+/g, '').match(/[\w-]+/g)
console.log(r) //=> [ 'this-is', 'my', 'example' ]
As per desired output. Get the matched group from index 1.
([\w-]+)|\+\s\w+\s\+
Live DEMO
MATCH 1 this-is
MATCH 2 my
MATCH 3 example
I need a (javascript compliant) regex that will match any string except a string that contains only whitespace. Cases:
" " (one space) => doesn't match
" " (multiple adjacent spaces) => doesn't match
"foo" (no whitespace) => matches
"foo bar" (whitespace between non-whitespace) => matches
"foo " (trailing whitespace) => matches
" foo" (leading whitespace) => matches
" foo " (leading and trailing whitespace) => matches
This looks for at least one non whitespace character.
/\S/.test(" "); // false
/\S/.test(" "); // false
/\S/.test(""); // false
/\S/.test("foo"); // true
/\S/.test("foo bar"); // true
/\S/.test("foo "); // true
/\S/.test(" foo"); // true
/\S/.test(" foo "); // true
I guess I'm assuming that an empty string should be consider whitespace only.
If an empty string (which technically doesn't contain all whitespace, because it contains nothing) should pass the test, then change it to...
/\S|^$/.test(" "); // false
/\S|^$/.test(""); // true
/\S|^$/.test(" foo "); // true
Try this expression:
/\S+/
\S mean any non-whitespace character.
/^\s*\S+(\s?\S)*\s*$/
demo :
var regex = /^\s*\S+(\s?\S)*\s*$/;
var cases = [" "," ","foo","foo bar","foo "," foo"," foo "];
for(var i=0,l=cases.length;i<l;i++)
{
if(regex.test(cases[i]))
console.log(cases[i]+' matches');
else
console.log(cases[i]+' doesn\'t match');
}
working demo : http://jsfiddle.net/PNtfH/1/
[Am not I am]'s answer is the best:
/\S/.test("foo");
Alternatively you can do:
/[^\s]/.test("foo");
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}