JavaScript Regex to remove text after a comma and the following word?


Let’s say the following is our string −

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);

We need to remove the text after comma and the following word i.e. after removing “I live in US” and keeping the rest. This would be the resultant string −

My Name is John, Smith

For this, use match() along with split().

Example

var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);
var expression = sentence.match(/([^,]*)(.*)/)[1];
var positionForComma = sentence.match(/([^,]*),(.*)/)[2].split(' ')[1]
var newValue = expression + ', ' + positionForComma
console.log("Updated="+newValue);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo175.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo175.js
The original value=My Name is John, Smith I live in US
Updated=My Name is John, Smith

Updated on: 12-Sep-2020

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements