我有一个字符串说例如
var str = "this is 'a simple' a simple 'string' string"
我想替换所有''字符,例如'p'字符。
str = "thip ip 'a simple' a pimple 'string' ptring"
采用这种方法的正确方法是什么?
答案 0 :(得分:5)
我们将其分解为令牌并以良好的方式解析它:
'
,请将您的州设置为“不替换”,否则将其设置为替换。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("");
答案 1 :(得分:2)
我会选择像
这样的功能splitStr = str.split("'");
for(var i = 0; i < splitStr.length; i=i+2){
splitStr[i].replace(/s/g, "p");
}
str = splitStr.join("'");
答案 2 :(得分:2)
这就是我要做的事情:
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"));
答案 3 :(得分:0)
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;
}
答案 4 :(得分:0)
JavaScript不支持前瞻和后瞻匹配,因此需要一些手工操作:
// 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();
});