2011-04-13 53 views
3

給出一個字符串,如下列中的一種:JavaScript字符串的正則表達式(CSS有效性檢查+轉化率)

'2' 
'2px' 
'2%' 
'2em' 
'2foobar' 
'foobar' 

我想確定:

1)是否是一個普通的數字(2 2)或'2.2'變成'2px'

2)如果它不是普通的(Math.floor())並附加'px'數字決定它是否是一個有效的CSS值,也就是說,它是否包含一個數字(int或float),後跟'px','em'或'%'。我知道還有其他人,但我會支持這三個。如果是,請保留它。

3)如果不是,看到如果字符串與多個(INT OT浮動開始),圓形,並附加「PX」

4),並且如果不是,則設置爲空字符串

這樣的結果將是:

'2'  -> '2px' 
'2.2' -> '2px' 

'2%' -> '2%' 
'2em' -> '2em' 

'2foo' -> '2px' 

'foo' -> '' 

是否有可能做到這一點以緊湊的方式(可能使用正則表達式),或者通過使用JS現有的CSS驗證庫?

+0

我發現這個http://docs.jquery.com/Plugins/Validation ..會看看它,看看它是如何被擴展,以驗證我在這裏需要的模式。 – mikkelbreum 2011-04-13 16:25:25

回答

7

這裏用一個正則表達式如何的:

var input = '2.7em', output = parseInt(input) + (input.match(/px|%|em/) || 'px') 

編輯:

var input = '2.7foo' 
, number = parseInt(input) 
, output = (isNaN(number)) ? '': number + (input.match(/px|%|em/) || 'px'); 

編輯2:允許浮動與EM和%:

var inp='3.5em' 
, n=parseFloat(inp), p=inp.match(/%|em/) 
, output = (isNaN(n)) ? '': (p)?n+p:Math.round(n)+'px'; 
+0

您的示例作品,我覺得它對於給定的問題最優雅,但如果input.match找不到其中的一個模式,我會得到一個錯誤。如果輸入設置爲'10foo',我會得到一個TypeError:No Prperties。看到這裏http://www.ideone.com/cwlgI你可以調整它來解決這個問題,那麼這將是一個完美的解決方案。 – mikkelbreum 2011-04-13 16:50:30

+0

調整,按要求:) – herostwist 2011-04-13 21:45:34

+0

這一個也有問題,在遊戲中太早轉換浮動到整數..浮動應該保持輸入包含'em'或'%'的小數點 – mikkelbreum 2011-04-14 16:12:30

2
var input = '2foo'; 
var output = ''; 
var tmp; 

tmp = parseInt(input.replace(/^[^1-9]*/, '')); 
if (tmp != 'NaN') { 
    if (tmp + '%' == input) { 
    output = tmp + '%'; 
    } else if (tmp + 'em' == input) { 
    output = tmp + 'em'; 
    } else { 
    output = tmp + 'px'; 
    } 
} 
+0

super,parseInt真正解決了所有這一切在這裏..有一點需要注意的是,根據http://www.w3schools.com/jsref/jsref_parseInt.asp任何前導零應處理之前從輸入條紋,因爲這會觸發八進制模式:parseInt('010')給出8 – mikkelbreum 2011-04-13 16:35:36

+0

http://www.ideone.com/AB45x和'0x10foo'給出271 http://www.ideone.com/PfcqB – mikkelbreum 2011-04-13 16:37:41

+0

我已編輯我的答案 - 它從一開始就消除了一切,不是1-9號碼。 – hsz 2011-04-13 16:40:48

0

如果你使用這個正則表達式替換你的數據,你只需要解決那些缺少前綴的問題。

^((?<whole>\d+)(\.\d+){0,1}(?<valid>px|em|pt|%){0,1}.*|.*)$ 

首先,

${whole}${valid} 

取代這個如果正則表達式不匹配,第二部分(|。*)都將匹配(什麼)和比賽將什麼也沒有更換。

你也可以一行一行地去掉&刪除那部分,當沒有匹配的時候,用javascript替換掉javascript。

最後,只是做一個快速的更換使用

^(?<justdigits>\d+)$ 

${justdigits}px 

所以更換,簡而言之:很多方面去了解這一點,取決於你如何繼續。

0

有趣的問題。這裏是使用一個正則表達式一個測試溶液和switch語句:

function clean_css_value(text) { 
    var re = /^(\d+(?:\.\d*)?|\.\d+)([^\d\s]+)?$/m; 
    // Case 0: String does not match pattern at all. 
    if (!(m = text.match(re))) return ''; 
    // Case 1: No number at all? return ''; 
    if (!m[1]) return ''; 
    var i = Math.floor(m[1]); // Compute integer portion. 
    // Case 2: Nothing after number? return integer pixels 
    if (!m[2]) return i + 'px'; 
    switch (m[2]) { 
    case 'em': 
    case '%': 
     return m[1] + m[2]; 
    case 'px': 
    default: 
     return i + 'px'; 
    } 
} 

注意,該功能也適用於不具有整數部分,例如分數.2px

0

以爲我會發布我現在使用的解決方案。爲了獲得語法着色,發佈了絕對路徑答案。這件事可以在這裏測試:http://jsfiddle.net/385AY/2/

這是非常冗長的,這裏的一些解決方案更加緊湊..但是對於任何人來說,爲什麼可以使用它,繼承人是一個更適合初學者的版本,以及有評論..

function css_value_validate(input) { 

    // first get rid of any whitespace at beginning or end of sting 
    input = $.trim(input); 

    // now catch any keywords that should be allowed 
    // this could be expanded for lots of keyword 
    // by holding allowed words in an object and 
    // checking against them 
    if (input == 'auto') { 
     return input; 
    } 

    // now get rid of anything that may precede the first occurence of a number or a dot 
    input = input.replace(/^[^0-9\.]*/, ''); 

    // add a leading zero if the input starts with a . and then a number 
    input = input.replace(/(^\.[0-9]*)/, "0$1"); 

    var output = ''; 
    var numeric; 

    // check of the input is a straight zero or an empty string and 
    if (input + '' === '0' || input + '' === '') { 
     return input; 
    } 

    // get the raw numeric by parsing to float 
    numeric = parseFloat(input); 
    if (numeric != 'NaN') { 
     if (numeric + '%' === input) { 
      output = numeric + '%'; 
     } else if (numeric + 'em' === input) { 
      output = numeric + 'em'; 
     } else { 
      // if converted to pixels strip any decimals. 
      // the 2nd parameter, 10, is the radix making sure we parse in decimal 
      output = parseInt(numeric, 10); 
      output = (output > 0) ? output + unit : output; 
     } 
    } 

    return output; 
} // END cssvalidate() 
+0

我不知道在這裏選擇哪個答案,你可以爲你的最愛投票,並添加一些意見,然後我會選擇最流行..(只有我可以選擇一個答案嗎?) – mikkelbreum 2011-04-14 16:08:38

0

當然,你問一個正則表達式...無論如何,它也可以通過從原始值解析值作爲整數或浮點數和它。

var input = '2.2px'; 
var value = parseInt(input) // => 2 
var unit = input.split(value)[1] // => 'px' 
相關問題