【vue】copy功能中替换字符串中的空格,换行符\r\n或\n去除

一:复制功能

export default {
	methods: {
		copy(value) {
			try{
				const textarea = document.createElement('textarea');
				document.body.appendChild(textarea);	//	添加到body中
				textarea.value = value;	//	给dom设置值
				textarea.select();	//	设置选中
				const copyFalse = document.execCommand('copy', false);
				if(copyFalse){
					this.alert('复制成功');
				}else{
					this.alert('复制失败');
				}
				textarea.remove();	//	用完移除dom
			} catch {
				this.alert('复制失败')
			}
		}
	}
}

二:字符串中的空格,换行符\r\n或\n替换

为了让回车换行符正确显示,需要将 \n 或 \r\n 替换成 <br>。同样地,将空格替换存 &nbsp;。这里我们通过正则表达式来替换。
一、替换所有的空格、回车换行符 
//原始字符串
var string = "欢迎访问!\r\nchifanlema.com";
//替换所有的换行符
string = string.replace(/\r\n/g,"<br>")
string = string.replace(/\n/g,"<br>");
 
//替换所有的空格(中文空格、英文空格都会被替换)
string = string.replace(/\s/g," ");
 
//输出转换后的字符串
console.log(string);

二、去掉所有的空格、回车换行符
//原始字符串
var string = "欢迎访问!\r\nchifanlema.com    ";
 
//去掉所有的换行符
string = string.replace(/\r\n/g,"")
string = string.replace(/\n/g,"");
 
//去掉所有的空格(中文空格、英文空格都会被替换)
string = string.replace(/\s/g,"");
 
//输出转换后的字符串
console.log(string);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不停喝水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值