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?
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);