Would it be possible to change this:
Hello, this is Mike [example]
to this:
Hello, this is Mike
Using JS + Regex? Thank you.
Would it be possible to change this:
Hello, this is Mike [example]
to this:
Hello, this is Mike
Using JS + Regex? Thank you.
Share Improve this question edited Sep 11, 2014 at 0:25 hwnd 70.7k4 gold badges98 silver badges135 bronze badges asked Sep 11, 2014 at 0:01 exomenexomen 4032 gold badges8 silver badges20 bronze badges 04 Answers
Reset to default 17If 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.
Based off your given string, you could just use split here.
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.
Or, as noted in the comments:
"Hello, this is Mike [example]".replace(/(\[.*?\])/g, '');
JS Fiddle demo.
References:
- JavaScript Regular Expressions.
Removal of the whitespace is not always desirable, e.g. 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."
This example shows removing '<' & '>', escaping using a text node function, removing divs and their content and finally removing '[' & ']'.
For a complete list of escape characters see: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);
// <a href="ggoggle.ca">ggogle</a> wish i was here <img src="image"> [square brackets]
str = str.replace(/\<.*?\>/g,'').replace(/\<.*?\>/g,'');
console.log('\n removed \'< >\' and escaped (< >) 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
}