I am trying to match the 1st character using regex in GAS. When I insert ^, the code doesn't work.If my id is "DEL", then I need words starting with "D", when id is "DEL" then all words strarting with "DEL".
function getAirportMatch(e) {
var airportlist = "`DELHI VIDP, MINDELIHM HEID, DELHI VIDD, LIHELD HDEL";
var id = "DEL";
var regExp = new RegExp("^(?:" id ")","gm"); // "i" is for case insensitive
var airport = regExp.exec(airportlist);
Logger.log(airport);````
CodePudding user response:
To match terms starting with something, use word boundary \b and matching everything up to the next comma (or end, which ever comes first):
"\b" id "[^,]*"
CodePudding user response:
If you simply want to see which airport names start with DEL you can simply make use of the startsWith method:
var airportlist = "DELHI VIDP, MINDELIHM HEID, DELHI VIDD, LIHELD HDEL";
var airportarray = airportlist.split(', ');
var id = "DEL";
airportarray.forEach(e => {if (e.startsWith(id.toString()))console.log(e)})
The snippet above creates an array with all the airport names and then checks if any of them start with the id you have supplied.
