user7058648
user7058648

Reputation:

Regex ,jquery issue

I'm using data-attribute and suppose I have a value: world is best (20052) and i want it as world is best - 20052

var a = $('[some-data-attribute]').text().replace(/\(|\)/g, '-');

This gives me: world is best -20052-.

However, I'd like it to get world is best - 20052.

Upvotes: 2

Views: 42

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You may use

console.log("world is best (20052)".replace(/\((\d+)\)/, "- $1"));

Details:

  • \( - a literal (
  • (\d+) - Group 1 (referred to with $1 backreference from the replacement pattern) - 1 or more digits
  • \) - a literal ).

If you have several such matches to handle, use the g modifier: /\((\d+)\)/g.

Upvotes: 3

Related Questions