Greg Witczak
Greg Witczak

Reputation: 1694

javascript equivalent to sed

I'd like to trim string, eg.

Pencil (4,99 USD)

to just a bracket numeric value:

4,99

I now a bit about regular expressions in sed, so I'd do that like this: sed "s#.*(##" | sed "s# USD.*##". But how should I use any regular expressions in javascript replace function?

Upvotes: 3

Views: 11922

Answers (3)

SwiftMango
SwiftMango

Reputation: 15294

I suggest you to do:

str.replace(/[^\d\.\,]/, "")

It means getting rid of everything that is not a digit, a comma, or a dot.

Upvotes: 2

Martin Ender
Martin Ender

Reputation: 44279

There is no need for replace here. Using the match function is probably easier and more appropriate:

var priceStr;
var match = "Pencil (4,99 USD)".match(/[\d,]+/)
if(match)
    priceStr = match[0];

You could refine the regex a bit. This one will simply give you the first substring made up of digits and/or commas. But if your string is always this short and of this format, it should be alright. However, if the name can contain numbers or commas you should probably start with the parenthesis and use a capturing group instead:

var priceStr;
var match = "Pencil, black, thickness 2 (4,99 USD)".match(/\(([\d,]+)/)
if(match)
    priceStr = match[1];

A short explanation for the latter regex. \( is just a literal opening parenthesis. The unescaped parentheses "capture" what is matched inside, so that you can later retrieve the price without that literal opening parenthesis. [\d,] is a character class, which matches either a digit or a comma, and + simply repeats the 1 or more times. And then we can retrieve the full match out of match[0] and the (first) capturing group out of match[1].

Upvotes: 8

Ωmega
Ωmega

Reputation: 43683

One of several possibilities is:

var match = "Pencil (4,99 USD)".match(/[^(]+(?= USD)/);

Upvotes: 0

Related Questions