例如,我有一个字符串说
var str = "this is 'a simple' a simple 'string' string"
我想将所有“s”字符替换为例如“p”字符。
str = "thip ip 'a simple' a pimple 'string' ptring"
解决这个问题的正确方法是什么?
例如,我有一个字符串说
var str = "this is 'a simple' a simple 'string' string"
我想将所有“s”字符替换为例如“p”字符。
str = "thip ip 'a simple' a pimple 'string' ptring"
解决这个问题的正确方法是什么?
我们将其分解为标记并以良好的方式解析它:
'
将您的状态设置为“不替换”(如果它正在替换),否则将其设置为替换。s
并且您的状态正在替换时,将其替换为p
此解决方案不支持'
.
var tokens = yourString.split("");
var inQuotes = false;
for(var i=0;i<tokens.length;i++){
if(tokens[i] == "'"){
inQuotes = !inQuotes;
}else
if(!inQuotes && tokens[i] == 's'){
tokens[i] = 'p'
}
}
var result = tokens.join("");
我会去一个像
splitStr = str.split("'");
for(var i = 0; i < splitStr.length; i=i+2){
splitStr[i].replace(/s/g, "p");
}
str = splitStr.join("'");
这是我要做的:
var str = "this is 'a simple' a simple 'string' string",
quoted = str.match(/'[^']+'/g);//get all quoted substrings
str =str.replace(/s/g,'p');
var restore = str.match(/'[^']+'/g);
for(var i = 0;i<restore.length;i++)
{
str = str.replace(restore[i], quoted[i]);
}
console.log(str);//logs "thip ip 'a simple' a pimple 'string' ptring"
当然,为了干净,我实际使用的代码是:
var str = (function(str)
{
var i,quoteExp = /'[^']+'/g,
quoted = str.match(quoteExp),
str = str.replace(/s/g, 'p'),
restore = str.match(quoteExp);
for(i=0;i<restore.length;i++)
{
str.replace(restore[i], quoted[i]);
}
return str;
}("this is 'a simple' a simple 'string' string"));
function myReplace(string) {
tabString = string.split("'");
var formattedString = '';
for(i = 0; typeof tabString[i] != "undefined"; i++){
if(i%2 == 1) {
formattedString = formattedString + "'" + tabString[i] + "'";
} else {
formattedString = formattedString + tabString[i].replace(/s/g, 'p');
}
}
return formattedString;
}
JavaScript 不支持lookahead 和lookbehind 匹配,因此需要一些人工操作:
// Source string
var str = "this is 'a simple' a simple 'string' string";
// RegEx to match all quoted strings.
var QUOTED_EXP = /\'[\w\s\d]+\'/g;
// Store an array of the unmodified quoted strings in source
var quoted = str.match(QUOTED_EXP);
// Do any desired replacement
str = str.replace('s', 'p'); // Do the replacement
// Put the original quoted strings back
str = str.replace(QUOTED_EXP, function(match, offset){
return quoted.shift();
});
小提琴:http: //jsfiddle.net/Zgbht/