替换文字"地图"用脚本

时间:2016-10-31 14:06:44

标签: javascript jquery

我想更改所有文字是" #"," /"和" + "使用JavaScript或jQuery。

如何更改此内容以显示在<div id="results"></div>上?

# =&gt; hash

/ =&gt; or

+ =&gt; plus

示例:

之前:G#7+

之后:Ghash7plus

之前:Fm/Ab

之后:FmorAb

我的代码:

<span class="teks">A</span>
<span class="teks">B</span>
<span class="teks">C#</span>
<span class="teks">G#7+</span>
<span class="teks">Fm/Ab</span>

<h3>RESULTS</h3>
<div id="results"></div>

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js' type='text/javascript'></script>

<script>
var textValues = $('.teks').map(function() {
thisCrd1 = $(this).html();
thisCrd2 = $(this).html();
    return "<div class='crd_"+ thisCrd1 + "'>"+ thisCrd2 + "</div>";
}).get();

$('#results').html(textValues);
</script>

我已经尝试了很多次,但显然没有得到我想要的结果。

3 个答案:

答案 0 :(得分:2)

您可以在replace()元素的文本上使用span函数以及全局正则表达式来替换所需的所有字符实例。

为了使维护变得简单,您可以将要替换的字符与替换放在您循环的对象中。试试这个:

&#13;
&#13;
var lookup = {
  '#': 'hash',
  '+': 'plus',
  '/': 'or'
}

$('span').text(function(_, t) {
  Object.keys(lookup).forEach(function(k) {
    t = t.replace(new RegExp('\\' + k, 'g'), lookup[k]);
  });
  return t;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="teks">A</span>
<span class="teks">B</span>
<span class="teks">C#</span>
<span class="teks">G#7+</span>
<span class="teks">Fm/Ab</span>
&#13;
&#13;
&#13;

要仅更新#results div,请尝试以下操作:

&#13;
&#13;
var lookup = {
  '#': 'hash',
  '+': 'plus',
  '/': 'or'
}

var spanText = $('span').map(function() {
  var t = $(this).text();
  Object.keys(lookup).forEach(function(k) {
    t = t.replace(new RegExp('\\' + k, 'g'), lookup[k]);
  });
  return t;
}).get()
$('#results').text(spanText.join(' '));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="teks">A</span>
<span class="teks">B</span>
<span class="teks">C#</span>
<span class="teks">G#7+</span>
<span class="teks">Fm/Ab</span>

<div id="results"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以尝试使用以下代码将#\+替换为相应的文本(前提是其他代码正常),

var thisCrd2 = thisCrd1.replace("#", "hash").replace("/", "or").replace("+", "plus");

答案 2 :(得分:0)

简单的正则表达式应该这样做。

&#13;
&#13;
var str = 'I want to change all of the text is "#", "/", and "+" using JavaScript or jQuery.';

console.log(
  str
  .replace(/#/ig,'hash')
  .replace(/\//ig,'or')
  .replace(/\+/ig,'plus')
)
&#13;
I want to change all of the text is "#", "/", and "+" using JavaScript or jQuery.

How to change this to appear on <div id="results"></div> ?

# => hash

/ => or

+ => plus
&#13;
&#13;
&#13;