Extract DOM className to only the desired className using a regular expression.

Asked 1 years ago, Updated 1 years ago, 84 views

Hello, I have a question about the regular expression, so I'm uploading it. In the case of multiple classnames as below, I would like to ask if there is a regular expression that extracts only classnames that meet the conditions.

Thank you for reading it.

regex javascript codesquad

2022-09-22 13:28

2 Answers

<div class="scrollbar-v scrollbar-show scrollbar-disabled goodDash badCamell forExample1">
  <p>Test</p>
</div>

Suppose the HTML file is the same as above.

let matched = [];

// You can obtain an array containing all the class names of the tags below
const classes = document.querySelector("div").classList

/*
 * Through the For Moon, I went around the Array's Element called Classes
 * You can obtain elements that meet these conditions.
*/

for (let i = 0, max = classes.length; i < max; i++) {
    if (/[-_]/g.test(classes[i])) {
        matched.push(classes[i]);
    }
}

console.log(matched);
// // ["scrollbar-v", "scrollbar-show", "scrollbar-disabled"]

If unlike the HTML file assumed now, there are many tags, and there are multiple classes in that tag at the same time,

If you need to delete Class Names that meet these criteria,

I think we can use the following function.

function solution(tag) {
  const tagList = document.querySelectorAll(tag);

  for (let i = 0, max = tagList.length; i < max; i++) {
    if (/[-_]/g.test(tagList[i].className)) {
      for (let j = 0, maxi = tagList[i].classList.length; j < maxi; j++) {
          if (/[-_]/g.test(tagList[i].classList[j])) {
            tagList[i].classList.remove(tagList[i].classList[j])
          }
      }
    }
  }
}

solution("div");

If it's not the answer you want, please leave a comment and we'll answer it.

Thank you.


2022-09-22 13:28

const className = 'scrollbar-v scrollbar-show scrollbar-disabled goodDash badCamell forExample1'; // tag.className;
console.log(className.match(/[^\s]*[-_][^\s]*(?=\s|$)/g));


2022-09-22 13:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.