从字符串中替换每第n个字符

4

我有这段 JavaScript 代码:

var str = "abcdefoihewfojias".split('');

for (var i = 0; i < str.length; i++) {
    var xp = str[i] = "|";
}
alert( str.join("") );

我想把字符串 abcdefoihewfojias 中每四个字母中的第四个字母替换成 |,使其变为 abc|efo|....etc,但我不知道该如何实现。

7个回答

7
您可以使用正则表达式替换完成此操作:

var str = "abcdefoihewfojias";
    
var result = str.replace(/(...)./g, "$1|");

console.log(result);


7
或许我评论得太早了,但你应该解释一下replace方法的工作原理和正则表达式的含义,这样才能完整地回答问题,让提问者和日后的用户明白它是如何工作的,以及为什么要这样做。 - David Thomas
我认为如果将正则表达式更改为/(.{3})./g,它会更清晰和可重用。 - FreeLightman

3
为了支持可重用性和将其包装在对象/函数中的选项,让我们对其进行参数化:
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("") );

如果你打算使用旧的方法,你应该使用charAt函数。 - Downgoat

2

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("") );

你可以使用for循环,从想要替换的第一个字符(第三个字符)开始,直到倒数第二个字符,并且每隔4个字符进行替换。

如果for循环从str.length开始而不是str.length-1,有时最后一个字符将会是|。


同意,但您需要解释您的答案,以便OP - 和任何未来的用户 - 可以理解为什么这样做有效。 - David Thomas

1
你可以使用这个一行代码:
var str = "abcdefoihewfojias";
str.split('').map(function(l,i) {
    return (i + 1) % 4 ? l : '|';
}).join('');

"

%返回余数。因此:

"
 # | Result (# + 1) % 4
---|-------
 0 | 1
 1 | 2
 2 | 3
 4 | 0 // Bingo!

ES6替代方案

使用ES6,您可以执行以下操作:

[...str].map((l,i) => (i + 1) % 4 ? l : '|')

0
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);

0

简单,只需使用模数运算符

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(""));

0

虽然已经有几个答案了,但我想提供一个稍微不同的方法,使用Array.prototype.map(),并将其包装在一个函数中,用户可以根据需要进行调整(以更新nnth字符中的值,并更改替换字符的使用):

// 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>

参考资料:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接