- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google