Ahmed Fathi
Ahmed Fathi

Reputation: 179

Get hashtags from string with trim spaces and new lines

textarea text and result console log

The javascript code:

How can I find hashtags without newline or spaces or tabs just hashtags without url hashtags?

function findHashtags(searchText) {
    var regexp = /\#\w\w+\s?/g
    result = searchText.match(regexp);
    if (result) {
        result.map(function(s) { return s.trim() });
        console.log(result);
    } else {
        return false;
    }
}

Upvotes: 7

Views: 14366

Answers (6)

Avinash Tare
Avinash Tare

Reputation: 1

function showTags(findTages) {
var text = findTages;
var tags = [];
for (let i = 0; i < text.length; i++) {
    if (text[i] == "#") {
        for (let l = i; l < text.length; l++) {
            if (text[l] == " ") {
                tags.push((text.substring(i, l)));
                break;
            };
        };
    };
};
return tags;

};

let a = I Love #Coding EveryTime Give Me Credit On Your Website My Name Is #Avi Boy; console.log(showTags((a)));

Upvotes: 0

Gaurav Patil
Gaurav Patil

Reputation: 1

Simple example.

<html>
<head>
    <script>
        function showTags(){
          var text = document.getElementById("text").value;
          var result = text.split(' ').filter(v=> v.startsWith('#'));
          document.getElementById("result").innerHTML = result;
        }
    </script>
</head>
<body>
    <h1>Enter text or paragraph</h1>

    <textarea type="text" id="text"></textarea><br>
    <button onclick="showTags()">Get Hashtags</button><br><br>
    <div id="result"></div>
</body>

Upvotes: 0

Sagiv Ofek
Sagiv Ofek

Reputation: 25280

If you care about readability simply do:

yourText.split(' ').filter(v=> v.startsWith('#'))

Upvotes: 11

Vishal Wayachal
Vishal Wayachal

Reputation: 49

Get hast tag from string

function getHashTag = function (tagString)
    {
      var tagListArray = [];
      var regexp = new RegExp('#([^\\s]*)', 'g');
      var tmplist = tagString.match(regexp);
      for (var w in tmplist) {
          var hashSub = tmplist[ w ].split('#');
          for (var x in hashSub) {
              if (hashSub[x] != "")
              {
                  if (hashSub[x].substr(hashSub[x].length - 1) == ":")
                  {
                      hashSub[x] = hashSub[x].slice(0, -1);
                  }
                  if (hashSub[x] != "") {
                      tagListArray.push(hashSub[x]);
                  }
              }
          }
      }
      return tagListArray;
    }

    console.log(getHashTag("#test#logic:main dummytext hello #stack:overflow"))

Upvotes: 2

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6810

Use \b instead of \s? - a word boundary instead of additional whitespace to not capture whitespace. Use \B (not a word boundary) to separate your url hashtags from urls that end in word characters.

So:

function findHashtags(searchText) {
    var regexp = /\B\#\w\w+\b/g
    result = searchText.match(regexp);
    if (result) {
        console.log(result);
    } else {
        return false;
    }
}

Which invoked thusly:

findHashtags("http://www.masrawy.com/Sports/Sports_News/details/2014/9/5/338281#HPOFEATURE\n#ss\nddd\n#ddd jaaja ksks #sfsfsf\n#ggdg#hdhhd")

Then returns:

["#ss", "#ddd", "#sfsfsf", "#ggdg", "#hdhhd"] 

Note that this will fail if the url ends in anything but a word character (a-z0-9_). The only option besides that would be to capture and more effectively trim whitespace:

function findHashtags(searchText) {
    var regexp = /(\s|^)\#\w\w+\b/gm
    result = searchText.match(regexp);
    if (result) {
        result = result.map(function(s){ return s.trim();});
        console.log(result);
        return result;
    } else {
        return false;
    }
}

Upvotes: 26

Paul S.
Paul S.

Reputation: 66404

Put the space match in a look-ahead, maybe with $ too

"#foo #bar #baz".match(/#[\w]+(?=\s|$)/g); // ["#foo", "#bar", "#baz"]

Now you can more easily modify the rest (i.e. add things next to \w) to match any valid hashtag

Upvotes: 2

Related Questions