单个正则表达式大写首字母并替换点

single regex to capitalize first letter and replace dot

本文关键字:替换 正则表达式 单个      更新时间:2023-09-26

尝试用正则表达式解决简单问题。我的输入字符串是

firstname.ab

我想把它输出为

Firstname AB

因此,主要目的是将字符串的第一个字母大写,并用空格替换点。于是选择了写两个正则表达式来求解。

First One:用空格/'./g

替换点

第二个:首字母/'b'w/g

大写

我的问题是,我们可以用一个正则表达式来做这两个操作吗?

提前感谢!!

您可以在replace中使用回调函数:

var str = 'firstname.ab';
 
var result = str.replace(/^([a-zA-Z])(.*)'.([^.]+)$/, function (match, grp1, grp2, grp3, offset, s) {
    return grp1.toUpperCase() + grp2 + " " + grp3.toUpperCase();
});
alert(result);

grp1grp2grp3代表回调函数中的捕获组。grp1是首字母([a-zA-Z])。然后我们捕获除换行符以外的任意数量的字符((.*) -如果您有换行符,请使用['s'S]*)。然后是文字点'.,我们没有捕获,因为我们想用空格替换它。最后,([^.]+$)正则表达式将匹配并捕获所有剩余的包含1个或多个字符的子字符串,而不是文字点,直到末尾。

我们可以使用捕获组以这种方式重新构建输入字符串

var $input = $('#input'),
    value = $input.val(),
    value = value.split( '.' );
value[0] = value[0].charAt( 0 ).toUpperCase() + value[0].substr(1),
value[1] = value[1].toUpperCase(),
value = value.join( ' ' );
$input.val( value );
It would be much easier if you simply split the value, process the string in the array, and join them back.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="first.ab" id="input">