JavaScript and Regex: Using a regular expression and .replace() to strip (foo) from a string

Here’s a quick tutorial on using regular expressions in JavaScript to edit a string and return the modified result. My strings looked like this:

"Toyota (1999 - 2005)"
"Ford (1995 and up)"
"Honda (up to 2015)"
"Kia or Chevy (any)

In this case, each string was the name property on an object. (Ie: you’re not looking at an array of strings in the example above.)

For display purposes, I wanted to show (in my app’s template) only what came before the first parenthesis, like so:

Kia or Chevy

Thanks to guide on how to use regex to remove everything after a particular character, and this refresher on how .replace() works, I had this problem solved in a matter of minutes with the following expression, where params[0] is the string (more about why my method looks like this after the code):

export function stripParensFromCarData(params/*, hash*/) {
  return params[0].replace(/\(.*\)/,'');

I used this method in an Ember helper I wrote to format strings for display in a handlebars template. The helper was hooked up like so in the .hbs file:

{{strip-parens-from-car-data carString}}

My favorite tool for testing regular expressions as I write them is

One thought on “JavaScript and Regex: Using a regular expression and .replace() to strip (foo) from a string”

Leave a Reply

Your email address will not be published. Required fields are marked *