parliament
parliament

Reputation: 22934

Javascript regular expression - number before percent sign

I have a string say:

 var currentLabel = "Uploading file... 0%"

This is the initial state when the upload starts and I need to update it as the operation runs. I need to take that 0 and replace it with a new number, however I can't just get a substring since it will change to 2 digits eventually and the length will change...

If the length was constant I could do:

var newLabel = currentLabel.substring(0, currentLabel.length - 2) + percent + "%";

I'm guessing I need a regular expression or really any other way.

Upvotes: 0

Views: 1120

Answers (4)

Antony Hatchkins
Antony Hatchkins

Reputation: 34004

You don't really need regexp in this case:

var currentLabel = "Uploading file... ";
var newLabel = currentLabel + percent + "%";

Upvotes: 0

Techmonk
Techmonk

Reputation: 1469

/.*([0-9]+)\%/ something like this will give you the number. but really this is a long way around to do this.

Upvotes: 0

Matthew
Matthew

Reputation: 9949

Certianally could be done with a regex and simple replacement

([\S\s]+?[\d]+([%])

Replace string

$1 "new percentage" $2

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191779

You could probably do it with a combination of indexOf and substring, but a regex does make it simpler:

newLabel = currentLabel.replace(/\d+$/, percent + "%");

There's no other numbers in the string, right?

You could also just write the string again .. it would probably be even less expensive than the regex.

Upvotes: 1

Related Questions