Link to home
Start Free TrialLog in
Avatar of Star79
Star79Flag for United States of America

asked on

Remove dashes and extract string using javascript

Hello,
I have a string 6850-01-347-0964
Please let me know how to extract the string into 2 different as following(first 4 and then the rest)
6850
013470964
using javascript
Thanks.
Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

You can use regular expression, it would be the perfect tool for this use case.
try:
let str="6850-01-347-09";
let parts = str.replace(/(\d+)-(\d+)/,"$1 $2").replace(/[-]/g,"").split(" ");
alert( parts[0] );//6850
alert( parts[1] );//0134709

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Let's look at the string like this.
You have parts separated by '-'
You are interested in the first part and then whatever comes after that.
We can do this using a combination of split and join. We split the string into its parts (separated by '-').
The first part is the 6850 bit you want separately - but it can be any length or combination of characters (given the rule we are separating on '-') - and the rest of the string is all parts except the first one.
With that in mind we can do
const str = "6850-01-347-0964";

// Split them
const parts = str.split('-');

// Get the first part
console.log('First part : ' , parts[0]);

// Get the rest
console.log('Rest : ', parts.slice(1).join('-'));

Open in new window

Be advised the accepted solution will not work if the first part of the string is not exactly 4 characters long
If your input is
const str = "685-01-347-0964";

Open in new window

The output will be
Part 1: 685-
Part 2: 013470964 

Open in new window

The above solution will produce this output for the same input
Part 1:  685
Part 2: 01-347-0964 

Open in new window

To remove the '-' you can amend like this (just remove the '-' from the join)
const str = "685-01-347-0964";

// Split them
const parts = str.split('-');

// Get the first part
console.log('First part : ' , parts[0]);

// Get the rest
// to Join without the '-' just remove it from the join call
console.log('Rest : ', parts.slice(1).join(''));

Open in new window

Which will produce the output
First part :  685
Rest :  013470964

Open in new window


If your input will always be 4 numbers followed by a '-' then you are good to go - however if the first part varies in length then your accepted solution will fail.
Avatar of Star79

ASKER

Good suggestion Julian, the first part is always going to be 4 numbers.