2

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.

2
  • 2
    It's a reasonably-asked question, but three upvotes for simple regex without any apparent due diligence? That seems odd to me. Commented May 24, 2017 at 20:43
  • .text() doesn't get the value of the data attribute, it gets the text content of the element. Use .data() too get the value of the attribute. Commented May 24, 2017 at 21:05

1 Answer 1

3

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.

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

1 Comment

I appreciate the power users, they give the best answers so OP and people viewing the question can learn the most!

Your Answer

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