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