感覺這應該很簡單
我有一些這樣的 html(我無法控制 html)
<div class="something" data-spec="['thing','another-thing','one-more-thing']">Stuff</div>
我正在嘗試將資料規范作為陣列讀取,而不必將其分解為字串,將其拆分然后將值推送到陣列中。
如果我這樣做:
let elem = $('.something')
let attr = elem[0].attributes['data-spec']
console.log(attr)
它回傳:
data-spec="['thing','another-thing','one-more-thing']"
有沒有辦法將 data-spec 作為陣列物件讀取?
謝謝。
uj5u.com熱心網友回復:
嘗試用雙引號替換所有單引號,然后使用 JSON.parse
const dataSpec="['thing','another-thing','one-more-thing']"
JSON.parse(dataSpec.replace(/'/g, '"'))
const dataSpec = "['thing','another-thing','one-more-thing']"
const array = JSON.parse(dataSpec.replace(/'/g, '"'))
console.log(array);
uj5u.com熱心網友回復:
否則我會這么說JSON.parse(),但由于這些是單引號,你不能直接這樣做。
可怕的選擇是eval(),但我認為一個快樂的中間立場(如果字串中有其他引號,它可能會中斷)是
const attrString = elem[0].attributes['data-spec'];
// replace single quotes with double quotes for JSON parsing
const attr = JSON.parse(attrString.replace(/'/g, '"'));
uj5u.com熱心網友回復:
不確定您是否可以直接做您想做的事情,但作為一種解決方法,您可以使用正則運算式來提取引號之間的所有內容,例如:
var test = "data-spec=\"['thing','another-thing','one-more-thing']\"";
var result = test.match(/(?<=\').*(?=\')/);
console.log(result);
//will log : Array [ "thing','another-thing','one-more-thing" ]
注意:也許您必須使用 JSON.stringify(elem[0].attributes['data-spec']) 才能擁有與示例中相同的字串“test”
uj5u.com熱心網友回復:
使用Vanilla方法querySelector獲取第一個具有class 的 匹配元素something。
const something = document.querySelector(".something");
const attr = something.dataset.spec; // You could also use something.getAttribute("data-spec")
console.log(attr); // "['thing','another-thing','one-more-thing']"
獲取報價之間的值,"'"使用match與標志克至匹配引號之間所有可能的值。
const elementsQuoted = attr.match(/'(.*?)'/g);//["'thing'", "'another-thing'", "'one-more-thing'"]
//Remove quotations by replacing any quote with empty string.
const array = elementsQuoted.map(element=>element.replaceAll("'",''));
結果
console.log(attr);//['thing', 'another-thing', 'one-more-thing']
注意:您可以通過正則運算式模式 /','/ 進行拆分以獲取陣列的值。但它只需要替換第一個元素中的左括號和最后一個元素的右括號。
attr.split(/','/g);//["['thing", 'another-thing', "one-more-thing']"]
永遠不要使用評估!
作為@AKX答案賺取利潤的JSON方法,parse用雙引號代替單引號,因為JSON標準要求雙引號,不接受單引號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371628.html
標籤:javascript 查询 数组 目的
