replacement of string using regular expression at Xth position intervals (javascript)

你说的曾经没有我的故事 提交于 2019-12-22 20:02:32

问题


I would very much appreciate some assistance from the community on replacing a string at xth position intervals, using javascript regex. For example, if the string length is 161 and the replacement text is <br />, regex would replace the string at the 40th, 80th, 120th, and 160th positions with this replacement text. Is this possible using regex?

Thank you very much.


回答1:


A method to add <br /> at ever 40th position is by using the following line:

string = string.replace(/([\S\s]{40})/g , "$1<br />");

If you want to dynamically set the position use:

var positions = 40;
var pattern = new RegExp("([\\s\\s]{" + positions + "})", "g");
string = string.replace(pattern , "$1<br />");

Explanation of the code:

  1. The first argument of the replace function is a RegExp:
    • ([\S\s] = all non-whitespace and white-space characters = every character).
    • {40} = 40 characters
    • The g flag means: global match, ie: match every possible occurence
    • The parentheses inside the RegExp means: Create a group. This group can later be referred by $1 (first group)
  2. The second argument of the replace function contains $1<br />. That is: replace the full match by the first group ($1), and add <br /> to it.



回答2:


var str = "12345678901234567890";
var newStr = str.replace(/(.{5})/g,"$1<br/>");

for every 40, change the 5 to 40.



来源:https://stackoverflow.com/questions/7930869/replacement-of-string-using-regular-expression-at-xth-position-intervals-javasc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!