JavaScript正则表达式删除逗号和以下单词后的文本?
假设以下是我们的字符串-
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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿