简体   繁体   中英

Insert a Text Element at Each First Position of a Comma Separated String

I have a hashtags-input field ( Input Field ) that saves the inputs comma separated. Now the problem is that people don't always type in a "#". Thats why I want to add it in front of each entered word afterwards.

Unfortuntately I'm having trouble creating a function that lets you add a "#" before each word, while the string is comma separated (not an array).

Does anyone has any idea how to achieve this?

Thanks!

supposing your string is hashtags , you could try

var corrected = hashtags.split(',') // separate by comma
  .map( word => "#" + word ) // add # to all
  .join(',') // recreate the string

but you probably need to check if there is already a # sign so this is better

var corrected = hashtags.split(',') // separate by comma
  .map( word => word[0] == "#" ? word : "#" + word ) 
     // add # to those who don't start with #
  .join(',') // recreate the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM