js中字符的替换(如用单引号提换双引号)

最近遇到一个问题,需要将Json转为String(  js中json对象和string互转 ),String对象内的单引号需要为双引号,就查了一下,做了一个总结。

JS提供的replace()方法正好解决了字符替换的问题。

 

stringObject.replace(regexp/substr,replacement)

 

参数描述
regexp/substr

必需。规定子字符串或要替换的模式的 RegExp 对象。

请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。

replacement必需。一个字符串值。规定了替换文本或生成替换文本的函数。

 

如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

 

 

 

 

下面是一个Json转String后,用双引号提换单引号;

 

<!DOCTYPE html >
<html > 
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="click" onclick="clickMe()" />
		<script type="text/javascript">
			var w = {a:"A",b:"B",c:"C"};
			function clickMe(){
				w = json2str(w);
				console.log(w);
				//引号提换
				w = w.replace(/'/g, '"');
				console.log(w);
			}
			/** 
			* json对象转字符串形式 
			*/ 
			function json2str(o) { 
			var arr = []; 
			var fmt = function(s) { 
			if (typeof s == 'object' && s != null) return json2str(s); 
			return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; 
			} 
			for (var i in o) arr.push("'" + i + "':" + fmt(o[i])); 
			return '{' + arr.join(',') + '}'; 
			} 
		</script>
	</body>
</html>

实现效果如下

 

全剧替换

 

<!DOCTYPE html >
<html > 
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="click" onclick="clickMe()" />
		<script type="text/javascript">
			function clickMe(){
				var str="Welcome to Microsoft! "
				str=str + "We are proud to announce that Microsoft has "
				str=str + "one of the largest Web Developers sites in the world."
				
				document.write(str.replace(/Microsoft/g, "W3School"))
			}
			
		</script>
	</body>
</html>

效果如下

 

把字符串中所有单词的首字母都转换为大写:

 

<!DOCTYPE html >
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<input type="button" value="click" onclick="clickMe()" />
		<script type="text/javascript">
			function clickMe() {
				name = 'aaa bbb ccc';

				uw = name.replace(/\b\w+\b/g, function(word) {
					return word.substring(0, 1).toUpperCase() + word.substring(1);
				});

				document.write(uw);

			}
		</script>
	</body>

</html>

结果如下

 


 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值