0

I'm checking if my string has special characters to replace but for the following string I'm having the following problem

String

(Lot P Verdes) 

Function

function retira_acentos(palavra) { com_acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ'; sem_acento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC'; nova=''; for(i=0;i<palavra.length;i++) { if (com_acento.search(palavra.substr(i,1))>=0) { nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1); } else { nova+=palavra.substr(i,1); } } return nova.toUpperCase(); } 

Error

line: if (com_acento.search(palavra.substr(i,1))>=0)

Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group

1
  • 2
    search uses regular expressions, and if you feed it strings, it tries to automatically convert them into one. But ( on its own is not a valid regular expression to begin with, because ( has a special meaning in regex. Commented Feb 11, 2019 at 14:27

2 Answers 2

1

The problem you've stumbled across here is that String#search requires a regexp as input, you, however, seem to want to search for a string input, not a regexp. In that case, use String#indexOf instead.

Try changing these lines and see if it gives you the desired output:

 if (com_acento.indexOf(palavra.substr(i,1))>=0) { nova+=sem_acento.substr(com_acento.indexOf(palavra.substr(i,1)),1); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Or String#includes.
@twhb Nope, includes returns a boolean but our friend here wants a number, as you can see in the middle line
@Ahmed Bajra Thank you very much, it worked. And I also understood now the reason for the error as explained.
0

In regular expression, round parenthesis are used to define groups. In this case, the regex parser thinks that you opened a group but you forgot to close it.

You don't want to open a group, I guess. You just want to match the literal character.

To match literal characters, in javascript regex, you have two ways:

  • Escape the character with the backslace: \. Example: /\(/

  • Wrap your character in square brackets. Example: [(]

In your case, it would be preferrable to use the second approach, because it works with any character (even with the ones that don't need to be escaped) and works also with many characters.

So I advise you to change the parameter of search in this way:

search('['+palavra.substr(i,1)+']') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.