在第X个位置间隔使用正则表达式替换字符串(javascript) [英] replacement of string using regular expression at Xth position intervals (javascript)

查看:83
本文介绍了在第X个位置间隔使用正则表达式替换字符串(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常感谢社区提供的一些帮助,以使用javascript正则表达式在xth位置间隔处替换字符串.例如,如果字符串长度为161并且替换文本为<br />,则regex将使用此替换文本替换在第40、80、120和160位的字符串.使用正则表达式可以吗?

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?

非常感谢您.

推荐答案

<br />添加到第40位的方法是使用以下行:

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

代码说明:

  1. replace函数的第一个参数是RegExp:
    • ([\S\s] =所有非空白字符和空白字符=每个字符).
    • {40} = 40个字符
    • g标志的意思是:全局匹配,即:匹配所有可能出现的情况
    • RegExp内的括号表示:创建一个组.此组以后可以由$1(第一组)
    • 引用
  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)

这篇关于在第X个位置间隔使用正则表达式替换字符串(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆