我有这个字符串:
"Test abc test test abc test test test abc test test abc"
Run Code Online (Sandbox Code Playgroud)
干
str = str.replace('abc', '');
Run Code Online (Sandbox Code Playgroud)
似乎只删除abc上面字符串中的第一次出现.如何更换所有出现的内容?
我想使用str_replace或类似的替代方法来替换JavaScript中的一些文本.
var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");
Run Code Online (Sandbox Code Playgroud)
应该给
this is some sample text that i dont want to replace
Run Code Online (Sandbox Code Playgroud)
如果您要使用正则表达式,与内置替换方法相比,性能影响是什么.
我试过这个:一次替换多个字符串 这个:javascript用数组全局替换它们如何不工作.
我可以这样做(它的PHP):
$a = array('a','o','e');
$b = array('1','2','3');
str_replace($a,$b,'stackoverflow');
Run Code Online (Sandbox Code Playgroud)
结果将是:
st1ck2v3rfl2w
Run Code Online (Sandbox Code Playgroud)
我想同时使用正则表达式.我怎样才能做到这一点 ?谢谢.
您可以使用数组进行替换:
var array = {"from1":"to1", "from2":"to2"}
for (var val in array)
text = text.replace(array, array[val]);
Run Code Online (Sandbox Code Playgroud)
但是,如果你需要全局替换,即text = text.replace(/ from/g,"to"),该怎么办?
数组相当大,因此如果我为每个变量写"text = text.replace(...)",脚本将占用大量空间.
在这种情况下你如何使用数组?"/ from1/g":"to1"不起作用.
我有一个大字符串,需要更换几次.如
var str="Username:[UN] Location:[LC] Age:[AG] ... "
str=str.replace("[UN]","Ali")
str=str.replace("[LC]","Turkey")
str=str.replace("[AG]","29")
...
//lots of replace
...
Run Code Online (Sandbox Code Playgroud)
有没有办法将这些FIND和REPLACE参数放到一个数组中,并立即替换所有这些参数?如:
reps = [["UN","Ali"], ["LC","Turkey"], ["AG","29"], ...]
$(str).replace(reps)
Run Code Online (Sandbox Code Playgroud) 我需要从 jQuery ajax 响应构建 HTML。我不喜欢在 javascript 中嵌套丑陋的字符串,也不想使用 Mustache 或任何其他模板脚本。
所以我采用了使用带有 display:none 的 HTML 模板的方法,如下所示:
<div id="message-template" class="message-tile" style="display: none;">
<div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
<div class="message-data">
<div class="message-info">
<div class="sender-name">
<a href="{{person-url}}">{{person-name}}</a>
</div>
<div class="posted-to">
To <a href="{{posted-to-url}}">{{posted-to-title}}</a>
</div>
</div>
<div>{{message-body}}</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我希望能够将 {{ }} 之间的字符串替换为 json 对象中的实际值。假设这是在 jQuery.ajax onSuccess 事件上调用的函数:
function createNewElement(jsonObj) {
var $clone = $('#message-template').clone();
$clone.replaceString("{{person-name}}", jsonObj.personName);
$clone.replaceString("{{thumb-url}}", jsonObj.thumbUrl);
$clone.replaceString("{{person-url}}", jsonObj.personUrl);
// etc
$("#target-container").append($clone);
}
Run Code Online (Sandbox Code Playgroud)
我发明了replaceString方法,但是有类似的东西吗?或者我是否需要使用 find() 遍历每个元素子元素?