samiles
samiles

Reputation: 3900

Javascript's replace for each word

I have a text box and, when the user hits space, I want each individual word to have a # prepended.

So far the code I have is:

  tagsNow = document.getElementById("tags").value;
  tagsChanged = tagsNow.replace(/(w+)/, "#$1");
  document.getElementById("tags").value = tagsChanged;

It partly works, as the # is prepended on the first time (word becomes #word).

However, if another word is typed, the # is just added right at the start of the text box, and it also adds another # if the user types their own #.

How could I solve these two problems?

Thanks

Upvotes: 0

Views: 287

Answers (2)

user943702
user943702

Reputation: 954

function tagify(str){
  return str.replace(/([^#]+?)(\s+|\b)/g, function(mat, grp1, grp2, at, src){
    return src[at-1] == "#" ? mat : "#" + mat;
  });
}

tagify("japan travel"); // "#japan #travel"
tagify("#torii bird");  // "#torii #bird"
tagify("C C#");         // "#C #C#"

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

I would imagine something like this would work:

tagsChanged = tagsNow.replace(/(^| )(?=!#)/g,"$1#");

This basically searches for spaces (and the start of the string) that don't have a # after them, and inserts that #.

Upvotes: 0

Related Questions