str = "#javas#cript ru forum# # 12345# #test1 test2 test3 test4# test1 test2 test3 test4#"; regexp = /(?:#\s?)((\S+\s+\S+\s+\S+)|(.*?#))/gi; newstr = str.match(regexp); alert(newstr);