Javascript正则表达式 - 用相同数量的另一个字符替换字符序列 [英] Javascript Regex- replace sequence of characters with same number of another character

查看:129
本文介绍了Javascript正则表达式 - 用相同数量的另一个字符替换字符序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用JavaScript中相同数量的虚拟字符替换部分字符串,例如:'== Hello =='with'== ~~~~~ =='。

I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.

此问题已通过 Perl PHP ,但我不能让它在JavaScript中工作。我一直在尝试这个:

This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:

txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");

模式匹配工作正常,但替换没有 - 第二部分添加'~~'代替模式匹配的长度。将$ 2放在括号内是行不通的。我该怎么做才能插入正确数量的字符?

The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?

推荐答案

使用替换函数代替:

var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
    return $1 + (new Array($2.length + 1).join("~")) + $3;
});

alert(txt);
//-> "==~~~~~=="

这篇关于Javascript正则表达式 - 用相同数量的另一个字符替换字符序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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