Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26652

Replace with javascript and regex

I want to replace a text like "New York (1224)" with only "New York".

I have var name = $(this).text().replace(' ()','')

That replaces "New York ()" with only "New York". But how can I make it with a regex that handles digits like in the example?

Upvotes: 0

Views: 73

Answers (4)

Pedro Lobito
Pedro Lobito

Reputation: 98881

You can use:

$(this).text().replace(/\s+\(\d+\)/g, "")

var str = "New York (1224)";
var replacement = str.replace(/\(\d+\)/g, "");
console.log(replacement);

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206024

Remove anything and wrapping parentheses

If you're not specifically interested in digits

\s*\([^)]*\)\s*$

will help you target anything enclosed in parentheses () and trim some spaces resulting in removing the highlighted portions like:

https://regex101.com/r/GyOc5X/1

Regex remove parentheses and it's content

Remove numbers and wrapping parentheses

otherwise, if you're strictly only interested in numbers wrapped in parentheses - and some whitespace trimming:

\s*\(\d+\)\s*$

https://regex101.com/r/GyOc5X/2

enter image description here

var name = $(this).text().replace(/\s*\(\d+\)\s*$/, "");   //New York

P.S:

  • If you want to also target the specific What () case from above than just replace \d+ with \d* like:
    \s*\(\d*\)\s*$
  • If you're flexible about End-of-string (meaning you have more text after the match) than simply remove the last $.

Upvotes: 1

jas7457
jas7457

Reputation: 1782

Try this:

var name = $(this).text().replace( /\(\d+\)$/,'')

This will replace any (number+) at the end of the string, but will not do it if it's anywhere else in the string. You can view http://regexr.com/3fqld to see what all it would replace

Upvotes: 0

baao
baao

Reputation: 73221

Use a regex

var name = $(this).text().replace(/\s\(\d+\)/,'');

Upvotes: 0

Related Questions