[英]How to replace dashes in a string?
我有一个这样的字符串:
d3f0c3cdf363-4303-8761-8e190f054be3
但是当我使用这段代码时:
const currentUserId = masterInfo.user.id.replace('-', '')
console.log('currentUserId', masterInfo.user.id.replace('-', ''))
我仍然得到这个:
currentuserId d3f0c3cdf363-4303-8761-8e190f054be3
如何删除-
的所有实例?
应该在你的正则表达式中传递一个g
:
const currentUserId = masterInfo.user.id.replace(new RegExp(/-/, 'gm'), ``)
演示:
const s = "d3f0c3cdf363-4303-8761-8e190f054be3" const test = s.replace(new RegExp(/-/, 'gm'), ``) console.log(test)
g
: global : 第一场比赛后不返回m
:多行: ^
和$
匹配行的开始/结束 使用replaceAll
而不是replace
。
replaceAll 替换所有出现的字符/字符串,并为替换工作添加一个全局标志。 参考这个
const currentUserId = masterInfo.user.id.replaceAll('-', '')
console.log('currentUserId', masterInfo.user.id.replaceAll('-', ''))
这是它的解决方案。 您也可以在此处运行并检查 output。
replaceAll
不适用于 react-native。
const message = 'd3f0c3-cdf363-4303-8761-8e190f054be3'; const result = message.replace(/-/g,''); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.