How to string replace and swap between 2 characters to replace with

时间:2018-03-25 20:03:45

标签: javascript jquery

Let me explain what I mean by the title (couldn't think of a better way to word it, sorry!)

How would I do a string replace, where it would replace all instances of a character in an array, but cycle between what I replace it with swapping from x to y.

For example, if I had a string that looked like this hello...., how would I run a string replace, and replace all the odd number characters with ! and even number characters with ? so my string looked like this hello!?!?

4 个答案:

答案 0 :(得分:2)

You could use a string for replacement where the index toggels between zero and one.

var string = 'hello....';
    
console.log(string.replace(/\./g, (i => _ => '!?'[i = 1 - i])(1)));

With an object.

var string = 'hello....';
    
console.log(string.replace(/\./g, (v => _ => v = { '!': '?', '?': '!' }[v])('?')));

答案 1 :(得分:0)

Give the replace function another function as an argument:

const getSwitchChar = (() => {
  let currentChar = 'b';
  return () => {
    if (currentChar === 'a') currentChar = 'b';
    else currentChar = 'a';
    return currentChar;
  };
})();

function switchReplace(str) {
  return str.replace(/e/g, getSwitchChar);
}
console.log(switchReplace('zzzeeeezzz'));

答案 2 :(得分:0)

Use a function as the second argument to replace. With each replacement, increment the symbol with replaceIndex (modulo the number of symbols):

const pattern = /[.]/g, // Matches each dot
  replaceWith = ["?", "!"];
let replaceIndex = 0;

console.log("hello....".replace(pattern, (dot) => (replaceIndex = (replaceIndex + 1) % replaceWith.length, replaceWith[replaceIndex])));

答案 3 :(得分:0)

Given let s = "hello....";

Then you can do:

let s = "hello....";
for (let i = 0; i < s.length; i++){
	if(s[i] == ".") // or your pattern here
    s = s.substr(0, i) + ((i % 2 == 0)? "?" : "!") + s.substr(i + 1);
}
console.log(s);

You can iterate through strings. So you can do a check for your character and replace the variable woth your modified string.