提问者:小点点

使用给定对象替换所有文本


我想替换HTML中的文本,它可能类似于以下内容

<span>Hello, I like mangoes.</span> 
Mango is also the <b>king</b> of fruits.
<p>Which fruit <div> is called the queen of fruits </div> </p>

使用给定的映射:

{
   "Hello, I like mangoes." : "New String",
   "Mango is also the " : "New String 1",
   "king" : "New String 2",
   "of fruits": "New String 3"
   .
   ..
}

如何使用jQuery将所有源字符串替换为映射中的值?

因此,转换后的HTML将如下所示:

<span>New String</span>
New String 1 <b>New String 2</b> New String 3
. . .

共2个答案

匿名用户

null

function replace($el, old, new_val){
  $el.html(function() { 
    return $(this).html().split(old).join(new_val);
  });
}

const $el = $('.container');

const data = {
   "Hello, I like mangoes." : "New String",
   "Mango is also the " : "New String 1",
   "king" : "New String 2",
   "of fruits": "New String 3",
};

for (let [old, new_val] of Object.entries(data)){
  replace($el, old, new_val);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <span>Hello, I like mangoes.</span> 
  Mango is also the <b>king</b> of fruits.
  <p>Which fruit <div> is called the queen of fruits </div> </p>
</div>

匿名用户

由于源字符串是对象中的键,因此需要使用object.keys()。 为了获得最好的结果,您将希望您的所有文本都在一个父对象中。

null

const map = {
  "Hello, I like mangoes.": "New String",
  "Mango is also the ": "New String 1",
  "king": "New String 2",
  "of fruits": "New String 3"
}

const run = () => {
  $("#box").html(function() {
    let text = $(this).html();
    Object.entries(map).forEach(([k, v]) => text = text.replace(new RegExp(k, 'g'), v));
    return text;
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="box">
  <span>Hello, I like mangoes.</span> Mango is also the <b>king</b> of fruits.
  <p>Which fruit is called the queen of fruits?</p>
</div>

<button onclick="run()">Run</button>