JavaScript 正则表达式删除逗号后面的文本和以下单词?

javascriptweb developmentobject oriented programming更新于 2025/11/18 2:52:17

假设以下是我们的字符串 −

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

我们需要删除逗号后面的文本和以下单词,即删除 “I live in US” 并保留其余部分。这将是结果字符串 −

My Name is John, Smith

为此,请使用 match() 和 split()。

示例

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);

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo175.js。

输出

这将产生以下输出 −

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

相关文章


有用资源