简体   繁体   中英

Why is my search() unable to find special characters?

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?

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?

Include this function in your code:

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

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM