0

I have, what I thought was, a simple regex to get anything not (letter), (number) or (%)

str.indexOf(/[^a-zA-Z0-9%]/);

However, I'm ALWAYS getting -1.

Here's an example str:

Check out this awesome video!

What am I doing wrong?

Randy Hall
  • 7,716
  • 16
  • 73
  • 151
  • 1
    The [`String.indexOf`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf) doesn't take a regular expression as argument. Instead, it takes another `String` as argument. Related: http://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr – BalusC Mar 21 '13 at 12:51
  • Why do you want to do this. Do you want to find a string? You want index of string? You want to replace something? As answered in the comments, `indexOf()` does not accept regex. Your requirements would narrow down other choices. – Jehanzeb.Malik Mar 21 '13 at 13:00
  • @Jehanzeb.Malik I'm running it in a `while` and replacing each character individually with its hex equivalent. – Randy Hall Mar 21 '13 at 13:21

2 Answers2

1

You cannot put regex into indexOf. Use search instead.

See this for more info: Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Community
  • 1
  • 1
Daedalus
  • 1,667
  • 10
  • 12
0
"Check out this awesome video!".replace(/./g,function(match){
  return '0x'+match.charCodeAt(0).toString(16);
});

returns the hexadecimal representation of the string. If you want just convert alpha-numeric characters, replace the . in the regex by \w.

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52