Kadhem
Kadhem

Reputation: 11

Visual Studio Code. Regex to search/replace just the apostrophe

I'm trying to find whatever starts with a word, followed by a ', and then followed by a word(/\w'\w/). For example(i'm, it's, what's,there's,John's), Take John's for example, it will match n's. That is perfect, but once that it is matched I want to replace just the ' and not n and s.

Upvotes: 0

Views: 922

Answers (3)

Scott Rudiger
Scott Rudiger

Reputation: 1300

Here's an alternative that doesn't use capturing groups, instead using a lookbehind and a lookahead:

const replaced = "John's it's I'm 'not this'".replace(/(?<=\w)'(?=\w)/g, '');

console.log(replaced);

Upvotes: 0

codedawi
codedawi

Reputation: 314

Yes use capture groups. Let's assume you want to replace the ' with ""

Match RegExp:

(\w)'(\w)

Replace with "":

$1""$2

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use capturing group.

([^'])'([^'])
   |     |________ Group 2
   |
   |______________ Group 1

let arr = [`i'm`, `it's`, `what's`,`there's`,`John's`]

arr.forEach(e=>{
  e = e.replace(/([^'])'([^'])/g, "$1$2")
  console.log(e)
})

  • Press Ctrl+f add regex pattern and select .* option.
  • In add replace value in the second input box $1$2

enter image description here enter image description here

Upvotes: 2

Related Questions