0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

new RegExp()

Posted at
title.rb
// ハイライト用関数
function highlight(text, keywords) {
  if (!keywords || keywords.length === 0) return text;
  
  // キーワードを正規表現に変換して置換
  const re = new RegExp("(" + keywords.map(k => escapeRegExp(k)).join("|") + ")", "gi");
  return text.replace(re, "<em>$1</em>");
}

// 正規表現用エスケープ
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// キーワード
const keywords = ["雨", "曇り"];

// field の中の一つを探して処理
const target = field.find(obj => Object.values(obj)[0].id === "3"); 
// id=3  { list3: { id: "3", data: "曇り" } } が取れる

if (target) {
  const value = Object.values(target)[0].data; // "曇り"
  const highlighted = highlight(value, keywords);
  console.log(highlighted); 
  //  <em>曇り</em>
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?