Search code examples
javascriptcssregexstylesheet

Regex - Match text between 2 characters


I need a regex pattern(s) that will match on words before a colon and also values between 2 characters. Here's the example, I have a string:

str='`width: 1070px; padding: 0px 10px 0px 10px; height: auto; margin:0px auto 0px auto;`' 

from a stylesheet, I need one array to store the property only (the text before a colon),

(prptyArray[0]='width', prptyArray[1]='padding') 

and another to store the value only (the text between 2 characters)

(valueArray[0]='1070px', valueArray[1]='0px 10px 0px 10px')

Thanks in advance.


Solution

  • ([\w-]+):\s*([#\w-\s\d]+);?

    Javascript does not have a method for submatch groups. exec only returns the 1st group found. Try exec in the online regular expression tester But still you could get the all the submatches in a fly. Try the following script,

    var str = "width: 1070px; padding: 0px 10px 0px 10px; height: auto; margin:0px auto 0px auto;";
    var value1 =[];
    var value2 =[]; 
    var tmp;
    
    do { 
        tmp = str;
        str = str.replace(/([\w-]+):\s*([\#\w-\s\d]+);?/,function($0,$1,$2){
            name1.push($1);
            name2.push($2);
            return $0.replace($1,"").replace($2,"");
        });
    
    } while(tmp!=str);
    
    alert(value1 +"\n"+value2);