var str = "text abc<span>span text</span>"; str = str.replace(/(\w+?)(?=<span>|$)/gi , "<a>$1</a>"); alert(str); str = "text abc"; str = str.replace(/(\w+?)(?=<span>|$)/gi , "<a>$1</a>") alert(str);