I have the following simple code:
<input id="nick" type="text"/>
<script>
var c = document.getElementById('nick').value
</script>
I need to remove a part of the name, only if it has square brackets []
. In other words, if it has this name: 'Hola soy juan [soy pro]'
, it would look like this: 'Hola soy juan'
.
An alternative is to use
replace
in conjunction with the regular expression 1/\[.+?]/g
where:\[
: escape the opening bracket..
: any character+
: One or more characters equal to the previous one?
: Stingy, the least number of timesg
: GlobalIn the following code, two cases are included, one similar to the one indicated by the OP and the other a bit more complex.
You can use substr and replace in a loop to remove all text inside
[ ]
For example, if you try 'Javier [the best] from [his house in] Panama' , the result will be
Javier de Panama
Then we remove all the repeated spaces with the code
output.replace(/\s+/g,' ').trim();
I hope it helps you
I have already done it in case anyone is interested: