Home > Web Front-end > JS Tutorial > How to implement string concatenation in JS (extending String.prototype.format)

How to implement string concatenation in JS (extending String.prototype.format)

亚连
Release: 2018-05-31 15:27:17
Original
2074 people have browsed it

这篇文章主要介绍了JS扩展String.prototype.format字符串拼接的功能,需要的朋友可以参考下

1、题外话,有关概念理解:String.prototype 属性表示 String原型对象。所有 String 的实例都继承自 String.prototype. 任何String.prototype上的改变都会影响到所有的 String 实例。

2、上正文,js扩展String.prototype.format字符串拼接的功能,首先是基础功能的改造:

String.prototype.format = function(){
  if(arguments.length==0){
    return this;
  }
  for(var s=this, i=0; i<arguments.length; i++){
    s = s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);
  }
  return s;
};
Copy after login

3、然后就是调用方式:

//方式1
var test = &#39;我的{0}是{1}&#39;;
var result = test.format(&#39;id&#39;,&#39;城市之光&#39;);
//方式2
var test = &#39;我的{name1}是{name2}&#39;;
var result = test.format({name1:&#39;id&#39;,name2:&#39;城市之光&#39;});
Copy after login

4、就这么简单,附带一个对trim()的扩展

String.prototype.trim = function() { 
 return this.replace(/(^\s*)|(\s*$)/g, ""); 
};
String.prototype.ltrim = function() { 
 return this.replace(/(^\s*)/g, ""); 
};
String.prototype.rtrim = function() { 
 return this.replace(/(\s*$)/g, ""); 
};
//调用方式
var eg1 = $(&#39;#id&#39;).val().trim();
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

vue获取当前激活路由的方法

vue 实现复制内容到粘贴板clipboard的方法

echarts鼠标覆盖高亮显示节点及关系名称详解

The above is the detailed content of How to implement string concatenation in JS (extending String.prototype.format). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template