我想用JavaScript写一个正则表达式。所以字符串可以被替换,但第一个和最后一个除外。
例如:
str="'Marys' Home'"我想在JavaScript中使用正则表达式,因此输出可以是:
"'Marys\' Home'"也就是说,除了由\'替换的第一个和最后一个单引号'。
我在Python中找到了类似的解决方案:Regular expression replace except first and last characters
发布于 2014-08-06 00:19:43
您可以使用以下命令:
var str = "'Marys' Home'";
var result = str.replace(/(?!^)(')(?!$)/g, '\\$1');
//=> 'Marys\' Home'发布于 2014-08-06 00:23:06
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, "'", "\'"))你在找这样的东西吗?
https://stackoverflow.com/questions/25143669
复制相似问题