How to write a regex for string matches which starts with @
or end with ,
. I am looking for a code in JavaScript.
RegEx solution would be:
var rx = /(^@|,$)/;
console.log(rx.test("")); // false
console.log(rx.test("aaa")); // false
console.log(rx.test("@aa")); // true
console.log(rx.test("aa,")); // true
console.log(rx.test("@a,")); // true
But why not simply use string functions to get the first and/or last characters:
var strings = [
"",
"aaa",
"@aa",
"aa,",
"@a,"
];
for (var i = 0; i < strings.length; i++) {
var string = strings[i],
result = string.length > 0 && (string.charAt(0) == "@" || string.slice(-1) == ",");
console.log(string, result);
}
For a string that either starts with @ or ends with a comma, the regex would look like this:
/^@|,$/
Or you, could just do this:
if ((str.charAt(0) == "@") || (str.charAt(str.length - 1) == ",")) {
// string matched
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With