famfamfam
famfamfam

Reputation: 545

How to replace dashes in a string?

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 -?

Upvotes: 0

Views: 114

Answers (3)

Virendrasinh R
Virendrasinh R

Reputation: 79

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);

Upvotes: 0

GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 9018

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

Upvotes: 1

Rohit Aggarwal
Rohit Aggarwal

Reputation: 1188

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('-', ''))

Upvotes: 0

Related Questions