1

Consider the following string

var string ="border-radius:10px 20px 30px 40px";

I want to take those 4 values(10,20,30,40) and store them in an array. To do that i wrote the following code:

var numbers=string.split('border-radius:');
numbers=numbers[1];
numbers=numbers.split("px");

My code is working five i get the output i want.My question is:Is there a cleaner code or a better code to achieve the same result? Here is my output:

["10", " 20", " 30", " 40", ""]
4
  • Use regex to extract the numbers Commented Jan 5, 2016 at 10:37
  • If that works for you, using split is probably the easiest and most efficient way to do it. Commented Jan 5, 2016 at 10:39
  • Refer stackoverflow.com/questions/2324633/… Commented Jan 5, 2016 at 10:39
  • I am new to programming and i have no idea about regex Commented Jan 5, 2016 at 10:40

2 Answers 2

2

You can use .match with Regexp

var string = "border-radius:10px 20px 30px 40px";
var result = string.match(/\d+/g);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Try:

var string ="border-radius:10px 20px 30px 40px";
var array = string.match(/[0-9]+/g);
alert(JSON.stringify(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.