const command = '(al)G(al)()()G' const o = {'(al)': 'al', '()': 'o'} const re = /\((al)?\)/g const val = command.replace(re,el => o[el]) alert(val)