javascript javascript中是否存在类似于gsub的东西?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7951768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:51:06  来源:igfitidea点击:

Does something similar to gsub exist in javascript?

javascriptjquerycssruby

提问by Nick

Is there any way to to do something similar to ruby gsub in javascript? I have a local html file that I want to process and replace certain template variables with content but I cannot figure out how to substitute out the template variables with the new content. The html contains fragments like below:

有没有办法在javascript中做类似于ruby gsub的事情?我有一个本地 html 文件,我想处理它并用内容替换某些模板变量,但我不知道如何用新内容替换模板变量。html 包含如下片段:

<div id="content">
    <h1>{{title}}</h1>
    {{content}}
</div>

Now if I wrap every template variables in a named div then I can use something like jquery's replaceAll method to replace the template variable with its content but I cant figure out how to do it without wrapping every variable in a div.

现在,如果我将每个模板变量都包装在一个命名的 div 中,那么我可以使用类似 jquery 的 replaceAll 方法来用其内容替换模板变量,但是如果不将每个变量包装在一个 div 中,我就无法弄清楚如何做到这一点。

I just want to do something like $('document').gsub("{{title}}", "I am a title").

我只想做一些类似 $('document').gsub("{{title}}", "I am a title") 的事情。

Anyone have any ideas?

有人有想法么?

Thanks for your help!

谢谢你的帮助!

采纳答案by gnab

You can access the raw HTML via a DOM element's innerHTMLproperty, or using JQuery's htmlproperty wrapping it, and then perform the substitution:

您可以通过 DOM 元素的innerHTML属性访问原始 HTML ,或者使用 JQuery 的html属性包装它,然后执行替换:

var html = $(document).html();
$(document).html(html.replace('{{title}}', 'I am a title');

EDIT:

编辑:

As pointed out by Antti Haapala, replacing the entire document HTML can have side-effects you don't want to deal with, like scripts being reloaded. Thus, you should drill down to the most specific DOM element possible before performing the substitution, i.e.:

正如 Antti Haapala 所指出的那样,替换整个文档 HTML 可能会产生您不想处理的副作用,例如重新加载脚本。因此,您应该在执行替换之前深入到最具体的 DOM 元素,即:

var element = $('#content');
var html = element.html();
element.html(html.replace('{{title}}', 'I am a title');

回答by Lri

If others were looking for an equivalent to gsub in general, this only replaces the first match:

如果其他人正在寻找与 gsub 等效的一般情况,这只会替换第一个匹配项:

"aa".replace("a", "b") // "ba"

//greplaces all matches:

//g替换所有匹配项:

"aa".replace(/a/g, "b") // "bb"
"aa".replace(new RegExp("a", "g"), "b"); // "bb"

回答by Antti Haapala

Well, you can use String.replace with a regex, but really, what you could use are jQuery Templates.

好吧,您可以将 String.replace 与正则表达式一起使用,但实际上,您可以使用的是 jQuery 模板。

http://api.jquery.com/category/plugins/templates/

http://api.jquery.com/category/plugins/templates/

回答by Kris

I recently used Handlebarsto take a data attribute (template) from a table and inject another value (record id) from one of its rows:

我最近使用Handlebars从表中获取数据属性(模板)并从其行中注入另一个值(记录 ID):

// data-row-url="http://example.com/people/{{id}}"

var table = $(this).closest('.data_grid table');                        

if(table.attr('data-row-url')) {                                        
    var record_id = $(this).data('record-id')                           
    var show_url_template = table.data('row-url');                      
    var url_template = Handlebars.compile(show_url_template)            
    var url = url_template({ id: record_id });                          
    $.getScript(url);                                                   
}  

For context this code runs from inside an onclick event for the table's tr elements and fetches the clicked record via ajax.

对于上下文,此代码从表的 tr 元素的 onclick 事件内部运行,并通过 ajax 获取单击的记录。

回答by Pedro Rolo

I believe that might be a mustache template. You might want to check mustache.js. I think you might be able to compile that to JS.

我相信这可能是一个小胡子模板。您可能想检查 mustache.js。我认为您可以将其编译为 JS。