将字符串替换为空字符串

Replace String with empty string

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

我有一个字符串,可以有以下子字符串值(也包括引号)

"+form"
"+ form "
" form+"
"form +"
+ form
+form
form+
form +
form   +
+    form
....
....
.... or just simply 'form' that doesnt surrounded by double quotes

问题是找到与以下

匹配的子字符串(+ form或form +)
  • '+ form'不应该被引号包围
  • 不限制'+'和'form'之间的空格数

    如果找到,则用空字符串"替换

    Input:
    ' form+ "form" +  form '
    Output:
    "form"
    

    输入:"形式"输出:"形式"

帮忙吗?

我只是在初学者的水平,似乎我不能解决这个简单的替换和索引方法:-(

var abc = string.replace(" " + "");
 if(abc.indexOf("+form") > -1 || abc.indexOf("form+") > -1 || abc.indexOf("form") > -1 || abc.indexOf("'"+form'"") > -1 || || abc.indexOf("'"form+'"") > -1 )
 {
    // then what should do?
 }

希望对您有所帮助

var input = ' form   + " form " +  form "  form +  " " +   form "'; 
var tmp = input.replace(new RegExp(/'"?'s*form's*'"?'s*'+'s*'"?/g), ''); //form +
tmp = tmp.replace(new RegExp(/'"?'s*'+'s*form's*'"?'s*'"?/g), '');// + form
alert(tmp);

必须创建两个正则表达式,一个用于+在'form'之前的情况,另一个用于+在'form'之后的情况。还有更好的办法。下面的注释有助于理解。

's* -> zero or more spaces  
'"? -> zero or one double quote  
'+  -> one + symbol  
/../g -> replace all matches

试试这个:

 var abc = string.replace(" ", "");
if (abc.indexOf("+form") > -1 {
    abc.replace("+form", "");
}
else if (abc.indexOf("form+") > -1) {
    abc.replace("form+", "");
}
else if (abc.indexOf("form") > -1) {
    abc.replace("form", "");
}
else if (abc.indexOf("'"+form'"") > -1) {
    abc.replace("'"+form'"", "");
}
else if (abc.indexOf("'"form+'"") > -1)) {
abc.replace("'"form+'"", "");
}

或:

var array = new Array();
array.push("+form", "form+", "form", "'"+form'"", "'"form+'"");
for (var i = 0; i < array.length; i++) {
if (abc.indexOf(array[i]) > -1) {
    abc.replace(array[i], "");
}

虽然使用正则表达式可能会更好。

你应该试试正则表达式。我知道它们很难创建,甚至更难阅读,但在这个网站上尝试一些:http://www.regexr.com/

下面是如何使用它们:http://www.w3schools.com/js/js_regexp.asp

然而,如果你不喜欢使用regexp,你可以尝试创建你的有限状态机,就像Nejc Lovrencic说的。

我尝试了一个小的正则表达式,得到了这个:

/[ 't'n'r+]+[^"]'w+[^"][ 't'n'r+]*/g

它是做什么的?它将尝试找到+或空字符(请纠正我,如果我错过了任何空白字符),没有引号,单词有多个字符,没有引号,+或空字符,它将全局查找,意味着每行。

更简单的方法是只查找"form":

/'"'w+'"/g

查找带引号的单词。

使用replace()函数将第一个大小写替换为空字符串

var result = intputString.replace("/[ 't'n'r+]+[^"]'w+[^"][ 't'n'r+]*/g", "");

包含引号和空字符串的单词将存储在result中。

如果你要用第二个大小写,你可以很容易地使用:

var regExp = /'"'w+'"/g var result = regExp.exec(intputString)

引号内的单词将存储在result中。

这些都是我在几分钟内做的正则表达式,但我相信你可以想出更具体的结果。

编辑:在第一种可能的情况下复制了错误的regexp,现在应该可以了