javascript简单替换引号内的所有内容

时间:2013-04-14 05:01:10

标签: javascript regex

令人惊讶,但我发现很难找到一个替换引号内文本的示例正则表达式。 E.g

  1. john went for a 'walk'
  2. john "walk" went for - 您可以了解任何订单
  3. 只会替换单词walk。

    我确实找到了这个:Regular Expressions - how to replace a character within quotes但是对于我想要做的事情来说,这似乎很复杂。

2 个答案:

答案 0 :(得分:2)

试用JavaScript正则表达式:

/(["'])[^]*?\1/g

这匹配双引号或单引号之间的任何内容。

针对您的具体情况:

var s = "john went for a 'walk'";
s.replace(/(["'])[^]*?\1/g, "run");

// "john went for a run"

var s = "john \"walk\" went for";
s.replace(/(["'])[^]*?\1/g, "run");

// "john run went for"

答案 1 :(得分:1)

怎么样

var string = "john went for a 'walk'";

var new_string = string.replace(/'([^;]*)'|"([^;]*)"/,"girl");

尝试http://jsfiddle.net/7dwCU/