1

I think this is a character encoding problem. My javascript search fails to identify a string whenever the string contains certain special characters such as ()* parenthesis, asterisks, and numerals.

The javascript is fairly simple. I search a string (str) for the value (val):

n = str.search(val);

The string I search was written to a txt file using PHP...

$scomment = $_POST['order'];
$data = stripslashes("$scomment\n");
$fh = fopen("comments.txt", "a");
fwrite($fh, $data);
fclose($fh);

...then retrieved with PHP...

$search = $_GET["name"];
$comments = file_get_contents('comments.txt');
$array = explode("~",$comments);
foreach($array as $item){if(strstr($item, $search)){
echo $item;  } }

...and put into my HTML using AJAX...

xmlhttp.open("GET","focus.php?name="+str,true);
xmlhttp.send();

My HTML is encoded as UTF-8.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

The problem is that the when I search() for strings, special characters are not recognized.

I didn't really see an option to encode the PHP created text, so I assumed it was UTF-8 too. Is that assumption incorrect?

If this is an encoding problem, how do I change the encoding of the txt file written with PHP? If it is caused by the above code, where is the problem?

user3283304
  • 149
  • 1
  • 2
  • 14
  • What is the $scomment value? What is actually being written to the text file? –  May 01 '15 at 16:19
  • Strings of text. Sentences. Some contain special characters like parenthesis, and these are the ones not recognized. – user3283304 May 01 '15 at 16:22
  • These are normal characters and should be searchable. There is something else that is going on in your code that is preventing the desired results. –  May 01 '15 at 16:25

2 Answers2

4

The search() function takes a regex. If a string is given, it is converted into one. Because of this, any special characters have special meanings, and it will not work as expected. You need to escape special characters.

Syntax

str.search(regexp)

Parameters

regexp

A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

If you want to search for text, use str.indexOf() instead, unless you NEED a regex. If so, see here on how to escape the string: Is there a RegExp.escape function in Javascript?

Community
  • 1
  • 1
James Wilkins
  • 6,836
  • 3
  • 48
  • 73
  • When you say I "need to escape special characters" does that mean there is no solution to find these characters? I just cannot have them in my search? – user3283304 May 01 '15 at 16:26
0

Include this function in your code:

function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

Hope it helps

Ritesh Karwa
  • 2,196
  • 1
  • 13
  • 17