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

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

问题描述

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

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

此问题已使用 PerlPHP,但我无法让它在 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 Regex-用另一个字符的相同数量替换字符序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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