简体   繁体   English

如何仅为匹配的正则表达式替换第一个字符?

[英]How to replace first character only for matched regex?

regOpenTags = new RegExp("<+[a-zA-Z]", "g");

matches html opening tags (eg <body> ) without matching closing tags (eg </body> ). 匹配html开始标记(例如<body> )而没有匹配的结束标记(例如</body> )。

I'd like to replace the first character of matched tags which is < , but doing 我想替换匹配标签的第一个字符< ,但正在做

parsedString = string.replace(regOpenTags, '');

would replace also the first letter. 也将取代第一个字母。 In other words, when using replace() on a string containing <body> , I'd prefer to get body> instead of ody> . 换句话说,当在包含<body>的字符串上使用replace()时,我更喜欢使用body>而不是ody>

How can I use the replace() method or regex to achieve this? 我如何使用replace()方法或正则表达式来实现这一目标?

You can use a Positive Lookahead to achieve this. 您可以使用Positive Lookahead来实现此目的。

regOpenTags = new RegExp("<(?=[a-z])", "gi");

Regular expression 正则表达式

<             '<'
(?=           look ahead to see if there is:
 [a-z]        any character of: 'a' to 'z'
)             end of look-ahead

See working demo 看工作demo

Another way of using a Positive Lookahead with negation . 使用带有否定的正向前瞻的另一种方式。

regOpenTags = new RegExp("<(?=[^/])", "g");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用正则表达式替换匹配字符串的最后一个字符 - Replace last character of a matched string using regex Javascript 正则表达式 - 仅将一个字符添加到匹配的字符串 - Javascript Regex - add only a character to matched string 如何使用RegEx仅获得第一个字符匹配 - How to get only first character match with RegEx JavaScript正则表达式替换 - 但只是匹配字符串的一部分? - JavaScript regex replace - but only part of matched string? 创建正则表达式以替换具有相同字符的字符串的每个匹配字符 - Creating a regex to replace each matched character of a string with same character String.Replace 仅替换匹配字符串的第一次出现。 如何替换*所有*出现? - String.Replace only replaces first occurrence of matched string. How to replace *all* occurrences? 使用jQuery / Regex替换子字符串中的最后一个匹配字符 - Replace last matched character in substring using jquery / regex Javascript,正则表达式:用空格和匹配的字符替换指定的字符 - Javascript, regex: Replace specified characters with space and matched character 如何在正则表达式的keyup上仅替换当前错误字符? - How to replace only current wrong character on keyup for regex? 如何在正则表达式的第一个字符中只允许“-”? - How can I allow only "-" at first character in regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM