简体   繁体   English

Javascript/regex:删除方括号之间的文本

[英]Javascript/regex: Remove text between square brackets

Would it be possible to change this:是否有可能改变这个:

Hello, this is Mike [example]

to this:对此:

Hello, this is Mike

Using JS + Regex?使用 JS + 正则表达式? Thank you.谢谢你。

If you prefer doing this using a regular expression, consider the following. 如果您更喜欢使用正则表达式执行此操作,请考虑以下内容。

var r = 'Hello, this is Mike [example]'.replace(/ *\[[^\]]*]/, '');
console.log(r); //=> "Hello, this is Mike"

If your data contains more text in brackets you want removed, use the g (global) modifier. 如果您的数据在要删除的方括号中包含更多文本,请使用g (全局)修饰符。

Based off your given string, you could just use split here. 根据给定的字符串,您可以在此处使用split。

var r = 'Hello, this is Mike [example]'.split(' [')[0]
console.log(r); //=> "Hello, this is Mike"

My first thought would be: 我的第一个想法是:

"Hello, this is Mike [example]".replace(/(\[.+\])/g, '');

JS Fiddle demo . JS小提琴演示

Or, as noted in the comments: 或者,如注释中所述:

"Hello, this is Mike [example]".replace(/(\[.*?\])/g, '');

JS Fiddle demo . JS小提琴演示

References: 参考文献:

Removal of the whitespace is not always desirable, eg when the brackets are used for some types of markup.删除空格并不总是可取的,例如,当括号用于某些类型的标记时。 Replace with a single space.替换为单个空格。

text = "This is a [big]large[/big] bear."
text = text.replace(/\s*\[.*?\]\s*/g, ' ')

result: text="This is a large bear."结果:text="这是一只大熊。"

This example shows removing '<' & '>', escaping using a text node function, removing divs and their content and finally removing '[' & ']'.此示例显示使用文本节点 function 删除 '<' & '>', escaping,删除 div 及其内容,最后删除 '[' & ']'。

For a complete list of escape characters see: mateam.net有关转义字符的完整列表,请参阅: mateam.net

function escapeHTML(html) {
  return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
}

var a = document.createElement('div');
a.id = 'test';
a.innerHTML = 'test';
document.body.appendChild(a);
a.onclick = function(){

var str = '<a href="ggoggle.ca">ggogle</a> wish i was here <img src="image"><div>another div</div> [square brackets] <div>yet another div</div>';

console.log('\n original string:\n'+str);

str = str.replace(/\<div\>.*?\<\/div\>/g,'');

console.log('\n removed divs & content:\n'+str);
// <a href="ggoggle.ca">ggogle</a> wish i was here <img src="image"> [square brackets]

var str = escapeHTML(str);

console.log('\n escape using text node - escapeHTML(html):\n'+str);
// &lt;a href="ggoggle.ca"&gt;ggogle&lt;/a&gt; wish i was here &lt;img src="image"&gt; [square brackets]

str = str.replace(/\<.*?\>/g,'').replace(/\&lt;.*?\&gt;/g,'');
    
console.log('\n removed \'< >\' and escaped (&lt; &gt;) and content:\n'+str);
// ggogle wish i was here  [square brackets] 

str = str.replace(/\[.*?\]/g,'')

console.log('\n remove square brackets and their content:\n'+str);
// ggogle wish i was here


}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM