How to write a regular expression for string matches that starts with @ or ends with @ I am looking for code in JavaScript.
@
RegEx solution will 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 just use string functions to get the first and / or last character:
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 line starting with @ or ending with a comma, the regex will look like this:
/^@|,$/
Or you could just do this:
if ((str.charAt(0) == "@") || (str.charAt(str.length - 1) == ",")) { // string matched }
'@test'.match(/^@.*[^,]$|^[^@].*,$/) // @test '@test,'.match(/^@.*[^,]$|^[^@].*,$/) // null 'test,'.match(/^@.*[^,]$|^[^@].*,$/) // test, 'test'.match(/^@.*[^,]$|^[^@].*,$/) // null
Source: https://habr.com/ru/post/892647/More articles:ViewModel View controller problem - iphoneHow to accept the average of big data in MongoDB and CouchDB? - mongodbThe fastest way to calculate the size of a file opened inside code (PHP) - fileHow to call a generic template function in a specialization version - c ++How to recognize where the application crashes? - iphoneOne value generates a gradient sequence more slowly in haskell than in c - haskellIncremental date string for 1 day - javaread selected value from select HTML tag using javascript code - javascriptHow can I get JSF 2.0 to include JS as "application / javascript" instead of "text / javascript", - javascriptHow to programmatically view a keyboard in a different language in an Android application? - androidAll Articles