0

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?

2
  • 1
    Maybe $(this).text().replace(/ \(\d+\)/g, '')? Commented Apr 24, 2017 at 20:56
  • Please clarify: 1) do you expect multiple values to be removed in 1 string? 2) is the value you need to remove always at the end of the string? Commented Apr 24, 2017 at 21:26

4 Answers 4

1

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 $.
Sign up to request clarification or add additional context in comments.

Comments

0

Use a regex

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

Comments

0

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

Comments

0

You can use:

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.