In my code, I have an array of elements. One of those elements is not a string (<a/>
element). I want to map through that array and find the element and, replace that element with the string 'error'. Here is the array. How can I achieve what I want?
const arr = ['my', 'array', '<a/>', 'is'];
CodePudding user response:
function checkHTML(str) {
let ele = document.createElement('div');
ele.innerHTML = str;
//check if node is of text
for ( let child of ele.childNodes){
if(child.nodeType !=3) return "error"
}
return str;
}
let arr=["my","<a/>","hi","<div>"]
let mappedArr = arr.map(checkHTML)
console.log(mappedArr)
CodePudding user response:
You can use regex to do it
var arr = ['my', 'array', '<a/>', 'is'];
const regex = /^<\w \/>$/
arr = arr.map(u =>
regex.test(u)?'error':u
);
console.log(arr);