zoukankan      html  css  js  c++  java
  • js replace常用用法

    1. 最简单
    var template = "this is a {img}";
    template = template.replace("{img}", "http://xxx");
    //this is a http://xxx
    
    2. 如果template中有两个同样的?
    var template = "this is a {img}, this {img} is beautiful";
    template = template.replace(/{img}/g, "http://xxx");
    //this is a http://xxx, this http://xxx is beautiful
    
    3. 如果"key"是不确定的?
    var config = {
    	"img" : "http://xxx",
    	"title" : "pig"
    }
    var template = "this is a {title}'s {img}, this {img} is beautiful";
    for(var i in config){
    	template = template.replace(new RegExp("{" + i + "}", "g"), config[i]);
    }
    //this is a pig's http://xxx, this http://xxx is beautiful
    
    4. 匹配到的
    var template = "this is word";
    template = template.replace(/(word)/g, "a $1");
    //this is a word
    
    5. 更复杂点的就用replace function
    var template = "this is word";
    template = template.replace(/\s(word)/g, function(word, p1){
    	//参数
    	//1. word:整个正则匹配到的 " word"  2. p1:(word)
    	return " a " + p1 + "," + word;  //" a word"
    });
    //this is a word, word
    

      

  • 相关阅读:
    Luogu 1514 引水入城
    HDU 2196 Computer
    CF460C Present
    初等数论整理
    2019UMS培训day6解题报告
    2019UMS培训day5解题报告
    2019UMS培训day3解题报告
    Luogu 1731 生日蛋糕
    JavaWeb之ServletContext域对象
    c3p0连接池
  • 原文地址:https://www.cnblogs.com/frostbelt/p/3022771.html
Copyright © 2011-2022 走看看