Alex Rivera | Logout

How to write a regex for string matches which starts with @ or end with ,?

Asked 2011-07-13T06:34:35.683
10

How to write a regex for string matches which starts with @ or end with ,. I am looking for a code in JavaScript.

Edit
Report

1 Answer

14

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);
}

answered 2011-07-13T06:38:40.297

Your Answer