Mapping and Replacing an Element of an Array

Viewed 32

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'];
3 Answers

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)

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);

You can simply achieve this with the help of RegEx by using String.match() method.

Live Demo :

const arr = ['my', 'array', '<a/>', 'is'];

arr.forEach((str, index) => {
  if (str.match(/<.*>/g)) {
    arr[index] = 'error';
  }
});

console.log(arr);

Related