Skip to content Skip to sidebar Skip to footer

Regex - Get All Characters After A Specific Character (#)

With the string below, how can I write a regular expression to remove or separately save only the characters that appear after the # symbol. var category = 'http://schemas.google.c

Solution 1:

You can use this regex:

var category = "http://schemas.google.com/g/2005#work";
var hashval = category.replace(/^[^#]*#([\s\S]*)$/, '$1');
//=> work

OR better using String#match:

var hashval = category.match(/#([\s\S]*)$/)[1];
//=> work

Solution 2:

The nice way is to let the browser do the heavy lifting.

var category = "http://schemas.google.com/g/2005#work",
    link = document.createElement('a'),
    hash;

link.href = category;

hash = link.hash;

This has your browser create an a element and set the the href property of that element to be category. The browser then parses the URL. The link's hash property is the bit after the # in the URL.

I answered a similar question some time ago, with a more worked-out version of this code.

Post a Comment for "Regex - Get All Characters After A Specific Character (#)"