How to Replace Every N-Th Character X from an String

Replace every nth character from a string

To support re-usability and the option to wrap this in an object/function let's parameterise it:

var str = "abcdefoihewfojias".split('');
var nth = 4; // the nth character you want to replace
var replaceWith = "|" // the character you want to replace the nth value
for (var i = nth-1; i < str.length-1; i+=nth) {
str[i] = replaceWith;
}
alert( str.join("") );

Replace every nth character equal to "x"

function replaceNth(str, n, newChar) {  const arr = str.split(',');  return arr.map((item, i) => (i % n === 0) ? item.replace('x', newChar) : item).join(",")}
const str = 'x1234,x2345,x3456,x4567,x5678,x6789';// replace for every second string valueconsole.log( replaceNth(str, 2, 'd'));// replace for every third string valueconsole.log( replaceNth(str, 3, 'e'));

How do i Replace every n-th character x from an String

Normally some own effort is demanded from the question, but regex is hard.

s = s.replaceAll("([^;]*;[^;]*;[^;]*);", "$1,");

A sequence of 0 or more of not-semicolon followed by semicolon and such.

[^ ...characters... ] is some char not listed.

...* is zero or more of the immediately preceding match.

The match of the 1st group (...) is given in $1, so actually only the last semicolon is replaced by a comma.

Replace every nth character with "-" in java without regex

What you could do is use a StringBuilder that will be initialized with your input String, then use setCharAt(int index, char ch) to modify a given char, this way you avoid building a new String at each iteration as you currently do with the operator += on String.

Something like:

public String everyNth(String str, int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be greater than 0");
}
StringBuilder result = new StringBuilder(str);
// This will replace every nth character with '-'
for (int i = n - 1; i < str.length(); i += n) {
result.setCharAt(i, '-');
}
return result.toString();
}

NB: Starts from n - 1 unless you want to replace the first character too if so starts from 0.


If you want to simply remove the characters, you should use the method append(CharSequence s, int start, int end) to build the content of your target String, as next:

public String everyNth(String str, int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be greater than 0");
}
StringBuilder result = new StringBuilder();
// The index of the previous match
int previous = 0;
for (int i = n-1; i < str.length(); i += n) {
// Add substring from previous match to the current
result.append(str, previous, i);
// Set the new value of previous
previous = i + 1;
}
// Add the remaining sub string
result.append(str, previous, str.length());
return result.toString();
}

How to find and replace every nth character occurrence using regex?

You can use:

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');

So if you are searching for every 3rd occurrence then use n-1 between {} in above regex.

To build it dynamically use:

let str = 'I amx nexver axt hoxme on Sxundxaxs';let n = 3;let ch = 'x';
let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");
str = str.replace(regex, '$1y');
console.log(str);//=> I amx nexver ayt hoxme on Sxundyaxs

Replace every nth occurrence of a string

using awk

$ awk '{for(i=1; i<=NF; i++) if($i=="is") if(++count%3==0) $i="hat"}1' file
is this just real life or is this just fantasy or hat it just me

Python - replace every nth occurrence of string

The code you got from the previous question is a nice starting point, and only a minimal adaptation is required to have it change every nth occurence:

def nth_repl_all(s, sub, repl, nth):
find = s.find(sub)
# loop util we find no match
i = 1
while find != -1:
# if i is equal to nth we found nth matches so replace
if i == nth:
s = s[:find]+repl+s[find + len(sub):]
i = 0
# find + len(sub) + 1 means we start after the last match
find = s.find(sub, find + len(sub) + 1)
i += 1
return s

How can I remove every nth character from a string in javascript?

You can use regex similar to your example. It stores a group of 5 characters with (.{5}) and matches an additional (6th) character with .. Then it replaces this with the group of 5 characters only, leaving out the 6th one.

const string = "You s$eem t%o be =very [happy? thes+e day$s!"
const saltedString = string.replace(/(.{5})./g,"$1")
console.log(saltedString)

C# - How to find and replace every nth character occurrence using C# or regex? Conversion from Javascript to C#

You can capture 2 non whitespace chars \S and match the 3rd non whitespace char.

In the replacement use the capture group followed by the character that you want in the replacement.

If you want to also match a space, you can use a dot . instead of \S