1

I have a string received from backend, and I need to extract hashtags. The tags are written in one of these two forms

type 1. #World is a #good #place to #live.
type 2. #World#place#live.

I managed to extract from first type by : str.replace(/#(\S*)/g how can i change the second format to space seperated tags as well as format one?

basically i want format two to be converted from

 #World#place#live.

to

 #World #place #live.
1
  • 1
    Try .replace(/\b#[^\s#]+/g, " $&") Commented Jan 19, 2019 at 12:25

3 Answers 3

1

You can use String.match, with regex #\w+:

var str = `
type 1. #World is a #good #place to #live.
type 2. #World#place#live.`

var matches = str.match(/#\w+/g)

console.log(matches)

\w+ matches any word character [a-zA-Z0-9_] more than once, so you might want to tweak that.

Once you have the matches in an array you can rearrange them to your likes.

Sign up to request clarification or add additional context in comments.

Comments

1

The pattern #(\S*) will match a # followed by 0+ times a non whitespace character in a captured group. That would match a single # as well. The string #World#place#live. contains no whitespace character so the whole string will be matched.

You could match them instead by using a negated character class. Match #, followed by a negated character class that matches not a # or a whitespace character.

#[^#\s]+

Regex demo

const strings = [
  "#World is a #good #place to #live.",
  "#World#place#live."

];
let pattern = /#[^#\s]+/g;

strings.forEach(s => {
  console.log(s.match(pattern));
});

Comments

0

How about that using regex /#([\w]+\b)/gm and join by space like below to extract #hastags from your string? OR you can use str.replace(/\b#[^\s#]+/g, " $&") as commented by @Wiktor

function findHashTags(str) {  
    var regex = /#([\w]+\b)/gm;
    var matches = [];
    var match;

    while ((match = regex.exec(str))) {
        matches.push(match[0]);
    }
    return matches;
}
let str1 = "#World is a #good #place to #live."
let str2 = "#World#place#live";
let res1 = findHashTags(str1);
let res2 = findHashTags(str2);
console.log(res1.join(' '));
console.log(res2.join(' '));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.