zallarak
zallarak

Reputation: 5515

JavaScript simple regular expression - limit string to have exactly '#' as first character

I basically want to parse a string such as:

"#FFFFFF"   to "#FFFFFF",
"##FFFFFF"  to "#FFFFFF",
"FFFFFF"    to "#FFFFFF"

I'm having issues making a generic regex expression that will handle cases like this. Any help would be appreciated.

Upvotes: 0

Views: 136

Answers (8)

scottheckel
scottheckel

Reputation: 9244

You will want to match any number of # OR then anything in the beginning. Like so (see jsFiddle):

new RegExp("(^#+|^)");

// #Test -> #Test
// ####Test -> #Test
// Test -> #Test

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Another solution to add to the mix that checks for a 3-6 letter hex code with or without a leading #.

var re = /#?([A-F0-9]{3,6})/i;
function getHex (str){
   var val = str.match(re)
   return val ? "#" + val[1] : null;
}

console.log( getHex( "#FFFFFF" ) ); 
console.log( getHex( "##FFFFFF" ) );
console.log( getHex( "FFFFFF" ) );

Upvotes: 0

Nick
Nick

Reputation: 9154

function formatThing(string){
    return "#" + string.replace(/#/g,"");
}

Replace all '#' with nothing, and stick a '#' on the front. In my opinion this is more readable than any convoluted regex. It works for all three of the inputs provided, as well as a few other odd cases.

Mind you, this is for converting as your question suggested you wanted, not matching. Better if you're trying to normalize different inputs, in that X to Y sense you wrote in the question. Taking "##FFFFFF" and matching all except the first "#", or refusing to match "FFFFFF" because it lacks a leading "#" wouldn't suffice here right off the bat.

Upvotes: 1

Code Jockey
Code Jockey

Reputation: 6721

I would replace any (or none) of the # characters at the beginning with a single instance of #:

resultString = sourceString.replace(/^#*/, "#");

Upvotes: 1

Strille
Strille

Reputation: 5781

This will not validate that the string is in fact a valid color, but just enforce that the string has exactly one hash as the first character (by stripping all hashes from the string no matter where they are and then adding one at the front):

var colorString = "##ffffff";

console.log("#" + colorString.replace(/#/g, "")); // prints #ffffff

Upvotes: 0

Diode
Diode

Reputation: 25135

var string = "#fffff";
string = string.replace(/#*/g, function(m, i){ return !i?"#":"";});

Upvotes: 1

HBP
HBP

Reputation: 16033

var str =  '###FFFF';
str = str.replace (/^#*/, '#')

Replaces 0 or more occurrences of # at the start of the string with a single #

Upvotes: 3

gcochard
gcochard

Reputation: 11744

You want something like /^[#][^#]*$/

Upvotes: 1

Related Questions