【问题标题】:Match anything after certain character匹配某个字符后的任何内容
【发布时间】:2020-01-29 06:10:56
【问题描述】:

如何替换某个字符之后的任何内容?例如:

var temp = 'abcdefghikj';

我想将c之后的所有字符都替换为空:

temp.replace('c*', '');

我查看了这个主题,但没有一个建议的解决方案对我有用: Regular Expressions- Match Anything

【问题讨论】:

  • temp = temp.substring(0, temp.indexOf("c") + 1);
  • 我不知道我做错了什么,但表达式 \?(.*) 对我不起作用。在我的情况下,我需要将其编辑为 \c(.*)\c.*,但在 temp.replace('\c.*', ''); 中使用时它不起作用

标签: javascript regex


【解决方案1】:

你写的是对的。你在那里:

var temp = 'abcdefghikj';
temp = temp.replace(/c(.*)$/ig, "c");
console.log(temp);

确保您还需要将返回值保存为原始值。

你不需要使用RegEx 这个简单的。您可以简单地找到c 的第一个索引并对其进行切片:

var temp = 'abcdefghikj';
temp = temp.substr(0, temp.indexOf("c") + 1);
console.log(temp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多