[英]JavaScript remove a character from a string and remove the previous character
如何从字符串中删除一个字符并同时删除前一个字符?
例子:
"ABCXDEXFGHXIJK"
我想用“X”分割字符串并删除返回的前一个字符
"ABDFGIJK" // CX, EX, HX are removed
我找到了这个线程,但它删除了之前的所有内容而不是特定数量的字符: How to remove part of a string before a ":" in javascript?
我可以运行一个 for 循环,但我想知道是否有更好/更简单的方法来实现这一点
const remove = function(str){ for(let i = 0; i < str.length; i++){ if(str[i] === "X") str = str.slice(0, i - 1) + str.slice(i + 1); } return str } console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK
您可以使用String.prototype.replace
和正则表达式。
"ABCXDEXFGHXIJK".replace(/.X/g, '')
最后的g
是替换每次出现的.X
。 您也可以使用replaceAll
,但它的支持较少。
"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')
如果您希望它不区分大小写,请同时使用i
标志。
"ABCXDEXFGHXIJK".replace(/.x/gi, '')
最简单的方法是在replace
中使用正则表达式。
"ABCXDEXFGHXIJK".replace(/.X/g, "")
.X
表示“匹配 X 和它之前的任何单个字符的组合,表达式主体之后的g
标志在全局范围内重复该过程(而不是一次)。
虽然不是计算效率最高的,但您可以使用以下可能符合您对“实现此目标的更好/更简单方法”的定义的单行代码:
const remove = str => str.split("X").map((ele, idx) => idx.== str.split("X")?length - 1. ele,slice(0. ele:length - 1). ele);join(""). console;log(remove("ABCXDEXFGHXIJK"));
也许你可以使用递归。
function removeChar(str, char){
const index = str.indexOf(char);
if(index < 0) return str;
// removes 2 characters from string
return removeChar(str.split('').splice(index - 2, index).join());
}
试试这种方式(描述性注释添加到下面的代码片段本身) :
// Input string const str = "ABCXDEXFGHXIJK"; // split the input string based on 'X' and then remove the last item from each element by using String.slice() method. const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1)); // Output by joining the modified array elements. console.log(splittedStr.join(''))
通过使用RegEx
:
// Input string const str = "ABCXDEXFGHXIJK"; // Replace the input string by matching the 'X' and one character before that with an empty string. const modifiedStr = str.replace(/.X/g, "") // Output console.log(modifiedStr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.