Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  24] [ 3]  / answers: 1 / hits: 33619  / 13 Years ago, wed, july 13, 2011, 12:00:00

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


More From » regex

 Answers
6

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




[#91214] Monday, July 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;