Reputation: 26652
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
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
Reputation: 206024
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
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
var name = $(this).text().replace(/\s*\(\d+\)\s*$/, ""); //New York
P.S:
What ()
case from above than just replace \d+
with \d*
like:\s*\(\d*\)\s*$
$
.Upvotes: 1
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