Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace little text format hashtag in string using javascript

I have a string returned by the LinkedIn API that contains a number of hashtags. They are formatted like this:

{hashtag|\#|somehashtag}

I am trying to use a regex with String.replaceAll that will replace all occurrence of these hashtags to a standard hashtag notation like this:

#somehashtag

I think this regex will identify the hashtags in the string, but how do I identify what would replace it as the second parameter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mystring.replaceAll(/(?<={hashtag\|\\\#\|)(.*)(?=})/g, /* whatgoeshere? */ );

So for example, if I have:

var mystring = "This is my social post, and it has a hashtag in it like this {hashtag|\#|somehashtag} and I want it replaced";

I want to be able to run something like:

mystring = mystring.replaceAll(regex, replacement)

So that this is returned in mystring:

"This is my social post, and it has a hashtag in it like this #somehashtag and I want it replaced"

>Solution :

You can use a capturing group (.*?) that captures the actual hashtag text. And in the second parameter to replace use the captured group using $1 along with #.

const regex = /{hashtag\|\\\#\|(.*?)}/g;
/* If it is a word character and that you're sure. 
 You can also use \w(matches [0-9a-zA-Z_]).
 so /{hashtag\|\\\#\|(\w*?)}/g
 https://regex101.com/r/zDTH6B/1 */
const mystring = "This is a {hashtag|\\#|samplehashtag} and another {hashtag|\\#|examplehashtag} in the text.";
const replaced = mystring.replace(regex, '#$1');

console.log(replaced);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading