Javascript用另一个String替换字符串

时间:2016-10-14 10:28:12

标签: javascript jquery

我在javascript中有以下字符串。

var str = 'P24 + P33'; //p24 is just exp. it will be any number i.e. P98

我想使用jquery replace将此字符串替换为以下字符串。

var str = "$('#p24').val() + $('#p33').val()";

1 个答案:

答案 0 :(得分:-1)

var str = 'P24 + P33'; //p24 is just exp. it will be any number i.e. P98
var str_array = str.split(" + ");
console.log("Original string: "+str);
for(var i = 0; i < str_array.length; i++){
  str_array[i] = $("#"+str_array[i]).html();
}
var replaced_string = str_array.join(" + ");
console.log("Replaced string: "+replaced_string);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="P24">this is P24</div>
<div id="P33">this is P33</div>