var str = "text abc<span>span text</span>"; str = str.replace(/^([a-z ]+?)(?=<span>|$)/gi , "<a>$1</a>"); alert(str); str = "text abc"; str = str.replace(/^([a-z ]+?)(?=<span>|$)/gi , "<a>$1</a>") alert(str);