简体   繁体   English

javascript 匹配获取所有包含数字的 class 名称

[英]javascript match get all class names with numbers in them

I'm trying to get the classes of the body tag that have numbers in them, but got stuck with the regex我正在尝试获取其中包含数字的 body 标签的类,但被正则表达式卡住了

<body class='UjQWin PEfnhb s21aSi'>

var matches = document.body.className.match(/[0-9]+/);
if (matches) {
    id = matches;
    //document.getElementById("num").innerHTML = id;
  console.log(id) //expected output s21aSi 
}

Is it possible to get the output as s21aSi in this case?在这种情况下,是否可以将 output 作为 s21aSi 获得?

You can create an array from the .classList property and filter that array, here is an example:您可以从.classList属性创建一个数组并过滤该数组,这是一个示例:

 const result = [...document.body.classList].filter(cl => /\d/.test(cl)); console.log(result);
 <body class='UjQWin PEfnhb s21aSi'>

You may split with whitespace ( .split(/\s+/) ) and filter using /\d/ (digit matching) pattern:您可以使用空格( .split(/\s+/) )拆分并使用/\d/ (数字匹配)模式进行过滤:

 var matches = document.body.className.split(/\s+/).filter(m => /\d/.test(m)); console.log(matches)
 <body class='UjQWin PEfnhb s21aSi'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM