[英]How to replace specific characters within a string in JavaScript?
Given a string like aaabba
, I want a function which turns the a's to b's and the b's to a's , returning bbbaab
. 给定像aaabba
这样的字符串,我想要一个函数,将a转换为b ,将b转换为a ,返回bbbaab
。
I tried this clumsy one: 我尝试了这个笨拙的方法:
var newa = [];
function swit(x) {
for (var i = 0; i < x.length; i++) {
if (x[i] === 'a') {
newa.push('b');
}
else if (x[i] === 'b') {
newa.push('a');
}
alert(newa);
}
}
swit("aaab");
After clicking through a lot of alerts, finally, the last alert shows the intended result. 单击大量警报后,最后一个警报将显示预期结果。 But I want it without commas and at the first place – not after many iterations: 但我希望它首先没有逗号–多次迭代之后:
I also tried the string.replace()
Method – in combination with a for
-loop: 我还尝试了string.replace()
方法–与for
-loop结合使用:
function swit(x) {
for (var i = 0; i < x.length; i++) {
if (x[i] === 'a') {
x.replace('a', 'b');
}
else if (x[i] === 'b') {
x.replace('b', 'a');
}
alert(x);
}
}
swit("aaab");
But nothing changes. 但是什么都没有改变。 Why? 为什么?
Could you please give me a hint of what went wrong and how to get the desired result? 您能否给我一些提示,指出出了什么问题以及如何获得期望的结果?
Easiest way is to split text to single characters using split
, then map array of chars by simply replace a => b
and b => a
and join
it together again, or just use replace
最简单的方法是使用split
将文本分割为单个字符,然后通过简单地替换a => b
和b => a
并将字符映射到字符数组,然后再次join
其连接在一起,或者仅使用replace
'bbbaab'.split('').map(char => char === 'a' ? 'b' : 'a').join('');
'bbbaab'.replace(/a|b/g, (match) => match === 'a' ? 'b' : 'a');
function swap(str) { return str.split('').map(char => char === 'a' ? 'b' : 'a').join(''); } function swap2(str) { return str.replace(/a|b/g, (match) => match === 'a' ? 'b' : 'a'); } console.log(swap('bbbaab')); console.log(swap2('bbbaab'));
var str = "aaab";
str = str.replace(/a|b/g, v => {
if(v=="a"){
return "b"
}else{
return "a"
}
});
console.log(str);
Your first example works but replaces a string with an array of characters (which is different from a string). 您的第一个示例有效,但是用一个字符数组(不同于字符串)替换了字符串。 You can simply join
the resulting array to get desired result: 您可以简单地join
结果数组以获得所需的结果:
function swit(x) {
var newa = [];
for (var i = 0; i < x.length; i++) {
if (x[i] === 'a') {
newa.push('b');
} else if (x[i] === 'b') {
newa.push('a');
}
}
var arrayJoined = newa.join('');
alert(arrayJoined);
return arrayJoined;
}
For your second example, replace
replaces all occurences in a string and does not need to be run in a for loop. 对于第二个示例, replace
替换字符串中所有出现的内容,并且不需要在for循环中运行。 So what you actually do in your second code sample is: for each character in string: if character is 'a', replace by b. if character is 'b', replace by a
因此,您在第二个代码示例中实际执行的操作是: for each character in string: if character is 'a', replace by b. if character is 'b', replace by a
for each character in string: if character is 'a', replace by b. if character is 'b', replace by a
. for each character in string: if character is 'a', replace by b. if character is 'b', replace by a
。 Which basically just switches all a
's to b
's and b
's back to a
's. 基本上,这只是将所有a
切换为b
,而b
切换回a
。 Which results in the same output string as your input string. 这将导致输出字符串与输入字符串相同。
You need to move your alert line out of the for loop to the end, and use Array.join() to convert newa
into a string without commas. 您需要将警报行从for循环中移到末尾,并使用Array.join()将newa
转换为不带逗号的字符串。
Also, it would make sense to move the newa
array declaration inside the swit
function. 此外,它将使意义移动newa
内部数组声明swit
功能。
Lastly, you should consider also adding an else condition where you just push the exact same current character onto the newa
array if it is not an a
or b
, so the output string length is the same as the original string. 最后,您还应该考虑添加else条件,如果不是a
或b
,则只需将完全相同的当前字符推入newa
数组,因此输出字符串的长度与原始字符串相同。
function swit(x) { var newa = []; for (var i = 0; i < x.length; i++) { if (x[i] === 'a') { newa.push('b'); } else if (x[i] === 'b') { newa.push('a'); } else { newa.push(x[i]) } } alert(newa.join("")); } swit("aaab"); swit("aasdfcvbab");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.