How to replace dashes in a string?

Viewed 30

I have a string like this:

d3f0c3cdf363-4303-8761-8e190f054be3

but when I use this code:

const currentUserId = masterInfo.user.id.replace('-', '')
console.log('currentUserId', masterInfo.user.id.replace('-', ''))

I still get this:

currentuserId d3f0c3cdf363-4303-8761-8e190f054be3

How can I remove all instances of -?

3 Answers

should pass a g in your Regex:

const currentUserId = masterInfo.user.id.replace(new RegExp(/-/, 'gm'), ``)

Demo:

const s = "d3f0c3cdf363-4303-8761-8e190f054be3"
const test = s.replace(new RegExp(/-/, 'gm'), ``)

console.log(test)

  • g: global: Don't return after first match
  • m: multi line: ^ and $ match start/end of line

here is the solution for it. you can run here and check output also.

replaceAll is not working with react-native.

const message = 'd3f0c3-cdf363-4303-8761-8e190f054be3';
const result = message.replace(/-/g,'');
console.log(result);

Use replaceAll instead of replace.
replaceAll replaces all occurrence of char/string and to make replace work add a global flag. Refer this

const currentUserId = masterInfo.user.id.replaceAll('-', '')
console.log('currentUserId', masterInfo.user.id.replaceAll('-', ''))
Related