假设以下是我们的字符串-
var sentence = 'My Name is John, Smith I live in US';
console.log("The original value="+sentence);我们需要删除逗号后的文字和以下单词,即删除“我住在美国”并保留其余内容。这将是结果字符串-
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