Posted in Javascript onAugust 11, 2020
核心代码
<script type='text/javascript'> String.format = function() { var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) { var reg = new RegExp("\\{" + i + "\\}", "gm"); s = s.replace(reg, arguments[i + 1]); } return s; } function stringFormat() { var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) { var reg = new RegExp("\\{" + i + "\\}", "gm"); s = s.replace(reg, arguments[i + 1]); } return s; } --用法 var name='3water.com'; var greeting1 = String.format("Hi--1, {0}, '{1}',this is a '{0}'! ", name, 'uuu'); var greeting2 = stringFormat("Hi--2, {0}, '{1}',this is a '{0}'! ", name, 'uuu'); alert(greeting1 + '\r\n' + greeting2); </script>
下面直接所有的字符串作为扩展
String.format = function() { for (var a = arguments[0], b = 1; b < arguments.length; b++) a = a.replace(RegExp("\\{" + (b - 1) + "\\}", "ig"), arguments[b]); return a };
使用方式 : String.format('Hello. My name is {0} {1}.', firstName, lastName);
为javascript添加String.Format方法
- Author -
mdxy-dxy声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@