[英]Replace every nth character from a string
I have this JavaScript:我有这个 JavaScript:
var str = "abcdefoihewfojias".split('');
for (var i = 0; i < str.length; i++) {
var xp = str[i] = "|";
}
alert( str.join("") );
I aim to replace every fourth letter in the string abcdefoihewfojias
with |
我的目标是将字符串
abcdefoihewfojias
中的每四个字母替换为|
, so it becomes abc|efo|....etc
,but I do not have a clue how to do this. ,所以它变成
abc|efo|....etc
,但我不知道如何做到这一点。
You could just do it with a regex replace: 您可以使用正则表达式替换来执行此操作:
var str = "abcdefoihewfojias"; var result = str.replace(/(...)./g, "$1|"); console.log(result);
This might help you solve your problem 这可能有助于您解决问题
var str = "abcdefoihewfojias".split(""); for (var i = 3; i < str.length - 1; i+=4) { str[i] = "|"; } alert( str.join("") );
You go with for loop from the the first char that you want to replace (the 3 char) until the one digit before the end and replace every 4 places. 你可以从你想要替换的第一个字符(3个字符)开始循环,直到结束前的一个数字,并替换每4个位置。
If the for loop will go from the str.length and not to str.length-1 sometimes at the last char will be |. 如果for循环将从str.length而不是str.length-1,有时在最后一个char将是|。
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("") );
Simple just use modulus 简单就是使用模数
https://jsfiddle.net/ctfsorwg/ https://jsfiddle.net/ctfsorwg/
var str = "abcdefoihewfojias";
var outputStr = str.split("");
for (var i = 0; i < outputStr.length; i++) {
if(!((i+1)%4))outputStr[i] = '|';
}
alert( "Before: " + str + "\nAfter: " + outputStr.join(""));
You can use this one-liner: 你可以使用这个单行:
var str = "abcdefoihewfojias";
str.split('').map(function(l,i) {
return (i + 1) % 4 ? l : '|';
}).join('');
%
returns the remainder. %
返回余数。 So: 所以:
# | Result (# + 1) % 4
---|-------
0 | 1
1 | 2
2 | 3
4 | 0 // Bingo!
With ES6, you can do: 使用ES6,您可以:
[...str].map((l,i) => (i + 1) % 4 ? l : '|')
While there are several answers already, I thought I'd offer a slightly alternative approach, using Array.prototype.map()
, wrapped in a function that can be adapted by the user (to update the value of n
in the nth
character, and change the replacement character used): 虽然已经有几个答案,但我认为我会提供一种稍微替代的方法,使用
Array.prototype.map()
,包装在一个可以由用户调整的函数中(更新第n
nth
字符中n
的值,并更改使用的替换字符):
// defining the named function, with an 'opts' argument:
function replaceNthWith(opts) {
// setting the default options:
var defaults = {
// defining the nth character, in this case
// every fourth:
'nth': 4,
// defining the character to replace that
// nth character with:
'char': '|'
};
// Note that there's no default string argument,
// so that one argument must be provided in the
// opts object.
// iterating over each property in the
// opts Object:
for (var property in opts) {
// if the current property is a property of
// this Object, not inherited from the Object
// prototype:
if (opts.hasOwnProperty(property)) {
// we set that property of the defaults
// Object to be equal to that property
// as set in the opts Object:
defaults[property] = opts[property];
}
}
// if there is a defaults.string property
// (inherited from the opts.string property)
// then we go ahead; otherwise nothing happens
// note: this property must be set for the
// function to do anything useful:
if (defaults.string) {
// here we split the string supplied from the user,
// via opts.string, in defaults.string to form an
// Array of characters; we iterate over that Array
// with Array.prototype.map(), which process one
// Array and returns a new Array according to the
// anonymous function supplied:
return haystack = defaults.string.split('').map(function(character, index) {
// here, when the index of the current letter in the
// Array formed by Array.prototype.split() plus 1
// (JavaScript is zero-based) divided by the number
// held in defaults.nth is equal to zero - ensuring
// that the current letter is the 'nth' index we return
// the defaults.char character; otherwise we return
// the original character from the Array over which
// we're iterating:
return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character;
// here we join the Array back into a String, using
// Array.prototype.join() with an empty string:
}).join('');
}
}
// 'snippet.log()' is used only in this demonstration, in real life use
// 'console.log()', or print to screen or display in whatever other
// method you prefer:
snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias" }) );
function replaceNthWith(opts) { var defaults = { 'nth': 4, 'char': '|' }; for (var property in opts) { if (opts.hasOwnProperty(property)) { defaults[property] = opts[property]; } } if (defaults.string) { return haystack = defaults.string.split('').map(function(character, index) { return (index + 1) % parseInt(defaults.nth) === 0 ? defaults.char : character; }).join(''); } } // 'snippet.log()' is used only in this demonstration, in real life use // 'console.log()', or print to screen or display in whatever other // method you prefer. // calling the function, passing in the supplied 'string' // property value: snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias" }) ); // outputs: abc|efo|hew|oji|s // calling the function with the same string, but to replace // every second character ( 'nth' : 2 ): snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias", 'nth': 2 }) ); // outputs: a|c|e|o|h|w|o|i|s // passing in the same string once again, working on every // third character, and replacing with a caret ('^'): snippet.log( replaceNthWith({ 'string': "abcdefoihewfojias", 'nth': 3, 'char' : '^' }) ); // outputs: ab^de^oi^ew^oj^as
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
References: 参考文献:
Array.prototype.map()
. Array.prototype.map()
。 Array.prototype.join()
. Array.prototype.join()
。 for...in
loop . for...in
循环 。 %
) operator . %
)运算符 。 Object.prototype.hasOwnProperty()
. Object.prototype.hasOwnProperty()
。 String.prototype.split()
. String.prototype.split()
。 function replaceWith(word,nth, replaceWithCh) {
//match nth position globally
//'\S' is for non-whitespace
let regex = new RegExp("(\\S{" + (nth - 1) + "})\\S", "g");
// '$1' means single group
// after each group position replaceWithCharecter
let _word = word.replace(regex, "$1" + replaceWithCh);
return _word;
}
const str = "abcdefoihewfojias";
const result = replaceWith(str, 3, "X");
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.