【问题标题】:JavaScript Regular expression replace except first and lastJavaScript正则表达式替换除第一个和最后一个
【发布时间】:2014-08-05 16:16:36
【问题描述】:

我想用 JavaScript 写一个正则表达式。所以字符串可以替换,但第一个和最后一个除外。

例如

str="'Marys' Home'"

我想要 JavaScript 中的正则表达式,所以输出可以是:

"'Marys\' Home'"

即除了第一个和最后一个单引号 ' 替换为 \'

我在 Python 中找到了类似的解决方案:Regular expression replace except first and last characters

【问题讨论】:

  • 你尝试过什么正则表达式?贴上你的代码,老兄。
  • 你为什么要这样做?

标签: javascript regex


【解决方案1】:

你可以用这个:

var str = "'Marys' Home'";

var result = str.replace(/(?!^)(')(?!$)/g, '\\$1');
//=> 'Marys\' Home'

RegEx Demo

【讨论】:

【解决方案2】:
var str = "'Marys' Home'"

function replace(str, pattern, replacement) {

  var firstIndex = str.indexOf(pattern)
    , lastIndex = str.lastIndexOf(pattern)
    , re = new RegExp(pattern, 'g')

  if (firstIndex < lastIndex) 
    str = str.substr(firstIndex + pattern.length, lastIndex)

  return str.replace(re, replacement)
}

console.log(replace(str, "'", "\'"))

您正在寻找类似的东西吗?

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多