通过正则表达式删除主题标签符号js

Sta*_*tas 3 javascript regex

尝试在论坛上搜索,但找不到任何与我需要的内容完全相同的内容。我基本上试图#从收到的结果中删除符号,这是正则表达式的虚拟示例。

let postText = 'this is a #test of #hashtags';
var regexp = new RegExp('#([^\\s])', 'g');
postText = postText.replace(regexp, '');

console.log(postText);
Run Code Online (Sandbox Code Playgroud)

它给出以下结果

this is a est of ashtags
Run Code Online (Sandbox Code Playgroud)

我需要更改什么才能仅删除主题标签而不删除每个单词的第一个字母

Wik*_*żew 5

您需要一个反向引用$1作为替换:

let postText = 'this is a #test of #hashtags';
var regexp = /#(\S)/g;
postText = postText.replace(regexp, '$1');
console.log(postText);
// Alternative with a lookahead:
console.log('this is a #test of #hashtags'.replace(/#(?=\S)/g, ''));
Run Code Online (Sandbox Code Playgroud)

注意我建议用正则表达式文字符号替换构造函数符号,以使正则表达式更具可读性,并[^\s]使用更短的字符\S(任何非空白字符)进行更改。

此处,/#(\S)/g匹配多次出现的(由于g修饰符)#及其后的任何非空白字符(同时将其捕获到组 1 中),并将String#replace找到的匹配项替换为后一个字符。

或者,为了避免使用反向引用(也称为占位符),您可以使用前瞻,如 中.replace(/#(?=\S)/g, ''),其中(?=\S)需要紧邻当前位置右侧的非空白字符。如果您还需要删除#字符串末尾的内容,则如果下一个字符是空格,则替换为该字符将使匹配失败(?=\S)(?!\s)