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>
结果如下





猜你喜欢

转载自blog.csdn.net/HGJacky/article/details/78216019