![](/img/trans.png)
[英]JS - Check if an array position contains a word and then return another word
[英]JS RegEx to return a hyphenated word and then another word/value
我遇到了一些正則表達式問題,但我的目標是讓這段代碼讀取諸如"background-colour:red;"
類的輸入。 ,驗證語法,然后將“背景顏色”和“紅色”放入數組中。 它目前返回["background-colour"]
,但不是紅色,我花了大約一個小時試圖弄清楚。 任何人都可以幫助或指出我正確的方向嗎? 我設法得到了像"opacity:1;"
這樣簡單的東西。 和"colour:red;"
工作,但連字符在其中扔了一個扳手。
let ed = document.getElementById("editor").innerText;
let dest = document.getElementById("destination");
//irrelevent code stripped here
regex3 = new RegExp(/^[a-zA-Z]+-[a-zA-Z]+:[a-zA-Z]+;$/i);
//irrelevent code stripped here
else if (regex3.test(ed)) {
console.log("valid input");
let pattern = /\w+\-\w+/g;
let temp = ed.match(pattern);
console.log(temp);
let att = temp[0];
let quant = String(temp[1]);
console.log(att);
console.log(temp);
dest.style.setProperty(att, quant);
使用正則表達式測試有效性並使用 split() 獲取數組中的屬性鍵和值。
const regex = /^\w+(-\w+:\w+)?/
const input = 'background-colour:red'
const valid = regex.test(input)
let ouput = []
if(valid){
ouput = input.split(":")
}
console.log(ouput)
您在示例中使用dest.style.setProperty
,所以我假設您正在使用 CSS 屬性。 此方法將為您提供所需的屬性和值,並適用於任何 CSS 值。
// test strings
const singleHyphenTest= 'background-color:red;';
const multipleHyphenTest = 'grid-template-columns:60px 60px;';
const noHyphenTest = 'color: red;';
const functionTest = 'width: calc(1rem + 20px);';
const customPropertyTest = 'background-color: var(--main-bg-color);';
const ANY_SYNTAX_WORKS = 'blablabla:stackoverflow;'
// either split the strings on : or ;
const pattern = /[:;]+/;
const singleGroup = singleHyphenTest.split(pattern);
const multipleGroup = multipleHyphenTest.split(pattern);
const noneGroup = noHyphenTest.split(pattern);
const functionGroup = functionTest.split(pattern);
const customGroup = customPropertyTest.split(pattern);
const anyGroup = ANY_SYNTAX_WORKS.split(pattern);
console.log(singleGroup); // ['background-color', 'red', '']
console.log(multipleGroup); // ['grid-template-columns', '60px 60px', '']
console.log(noneGroup); // ['color', ' red', '']
console.log(functionGroup); // ['width', ' calc(1rem + 20px)', '']
console.log(customGroup); // ['background-color', ' var(--main-bg-color)', '']
console.log(anyGroup); // ['blablabla', 'stackoverflow', '']
您可以通過檢查數組長度是否等於 3 來檢查 CSS 是否“有效”:
const ed = 'background-color:red;';
const pattern = /[:;]+/;
const groups = ed.split(pattern);
if (3 === groups.length) {
const [cssProperty, cssValue] = groups;
console.log(cssProperty); // background-color
console.log(cssValue); // red
// do your stuff here
// dest.style.setProperty(cssProperty, cssValue);
}
同樣:此解決方案(以及您示例中的正則表達式)不驗證語法! 它只做一些基本的模式匹配。 為了驗證 CSS 語法,你必須做更多的事情來捕捉所有邊緣情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.