Ahsan Ali Ahsan Ali - 4 months ago 9
Javascript Question

Replace text in javascript, jquery

var input="gazanie, flower, blossom";


I need to replace var text using JavaScript or jQuery.

Output should be like:

"#gazanie #flower #blossom"

Answer
"gazanie, flower, blossom".split(',').map((e)=>`#${e.trim()}`).join('');

THat's it :

  • split : to split string according to delimitor which is , & get array
  • map : to add prefix for each element which is #
  • trim : eliminate space if it is the 1st char or/and is the last char.
  • join : to return back from Array to String .

DEMO :

var input="gazanie, flower, blossom";

var output=input.split(',').map((e)=>`#${e.trim()}`).join(' ');
console.log(output);

Comments