s_p
s_p

Reputation: 4693

regex remove hash element from array items

I am using regex to capture hashtags from a string like this:

var words = "#hashed words and some #more #hashed words";
var tagslistarr = words.match(/#\S+/g); 

console.log(tagslistarr);

this will return an array like this;

["#hashed", "#more", "#hashed"]

question: how can i remove the # hash sign from each of the array items? this is what i would like in the end

["hashed", "more", "hashed"]

Upvotes: 1

Views: 466

Answers (4)

Ethan Brown
Ethan Brown

Reputation: 27282

Try:

words.match( /#\S+/g ).map( function(x) { return x.replace(/^#/,''); } );

A better way to do this would be zero-width assertions; unfortunately, JavaScript does not support look-behind assertions, only look-ahead. (As an aside, here is a blog post about mimicking lookbehind assertions in JavaScript. I can't say as I care much for any of the solutions, but it's good reading nonetheless. I sure hope lookbehind assertions make it into ES6.)

As pointed out by SimonR in the comments below, Array.prototype.map is not available in IE8 and below. However, it's easy enough to polyfill:

if( !Array.prototype.map ) {
    Array.prototype.map = function(f) { 
        var r = []; 
        for( var i=0; i<this.length; i++ ) r[i] = f(this[i]); 
        return r; 
    }
}

Upvotes: 5

falsetru
falsetru

Reputation: 369274

var words = "#hashed words and some #more #hashed words";
var tagslistarr = words.match(/#\S+/g); 
tagslistarr = tagslistarr.map(function(x) { return x.substr(1); } );
console.log(tagslistarr)

prints

["hashed", "more", "hashed"]

Upvotes: 4

Paul
Paul

Reputation: 141877

var words = "#hashed words and some #more #hashed words";
var regexp = /#(\S+)/g; // Capture the part of the match you want
var results = [];
var match;
while((match = regexp.exec(words))) // Loop through all matches
  results.push(match[1]);           // Add them to results array

console.log(results);

Upvotes: 1

SimonR
SimonR

Reputation: 1268

Use a capturing group in your regex:

words.replace(/#(\S+)/g, '$1');

EDIT:

To get them as an array:

var tagslistarr = words.match(/#\S+/g);

for( var i = 0, l = tagslistarr.length; i < l; i++ ) {
  tagslistarr[ i ] = tagslistarr[ i ].substr( 1 );
}

Upvotes: 2

Related Questions