替换字符而不替换''在字符串中

replacing a character without replacing anything within ' ' in a string

本文关键字:替换 字符串 字符      更新时间:2023-09-26

我有一个字符串,比如

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不支持先行和后向匹配,因此需要一些人工:

// 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();
});

Fiddle:http://jsfiddle.net/Zgbht/