在每次出现其他多个子字符串后追加字符串

时间:2018-03-09 21:37:24

标签: javascript

假设我将以下字符串存储在变量中,比如txt1

<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscs" href="javascript:void(0)">1. fcfs.cs</a>&nbsp;&nbsp;<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscs" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscpp" href="javascript:void(0)">2. fcfs.cpp</a>&nbsp;&nbsp;<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscpp" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfspy" href="javascript:void(0)">3. fcfs.py</a>&nbsp;&nbsp;<i id="myStaroperatingsystemsrcfirstcomefirstservefcfspy" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfsrs" href="javascript:void(0)">4. fcfs.rs</a>&nbsp;&nbsp;<i id="myStaroperatingsystemsrcfirstcomefirstservefcfsrs" class="fa fa-star"></i><br><a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstserveFCFSjava" href="javascript:void(0)">5. FCFS.java</a>&nbsp;&nbsp;<i id="myStaroperatingsystemsrcfirstcomefirstserveFCFSjava" class="fa fa-star"></i><br>

现在我想在字符串中的每个style='color: rgb(255, 255, 255); font-weight: bold'之后插入a target="_blank

我怎样才能使用javascript?

2 个答案:

答案 0 :(得分:1)

如果您可以轻松使用CSS来设置相应元素的样式,为什么要使用Javascript来修改HTML字符串:

a[target="_blank"] + * {
  color: /* rgb(255, 255, 255) */
  red;
  font-weight: bold;
}
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">

<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscs" href="javascript:void(0)">
  	1. fcfs.cs
</a>
&nbsp;&nbsp;
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscs" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfscpp" href="javascript:void(0)">
  2. fcfs.cpp
</a>
&nbsp;&nbsp;
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfscpp" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfspy" href="javascript:void(0)">
  3. fcfs.py
</a>
&nbsp;&nbsp;
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfspy" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstservefcfsrs" href="javascript:void(0)">
  4. fcfs.rs
</a>
&nbsp;&nbsp;
<i id="myStaroperatingsystemsrcfirstcomefirstservefcfsrs" class="fa fa-star"></i>
<br>
<a target="_blank" id="myIdoperatingsystemsrcfirstcomefirstserveFCFSjava" href="javascript:void(0)">
  5. FCFS.java
</a>
&nbsp;&nbsp;
<i id="myStaroperatingsystemsrcfirstcomefirstserveFCFSjava" class="fa fa-star"></i><br>

答案 1 :(得分:0)

如果我绝对必须这样做,我会使用String#replace。但我会先尝试很难找到基于CSS的解决方案。

const substring = 'a target="_blank"'
const replacement = '$& style="color: rgb(255, 255, 255); font-weight: bold"'

txt1.replace(substring, replacement)