Carmela
Carmela

Reputation: 687

How to determine if there are foreign characters (not from English alphabet) in a string?

I am storing google maps result in my database and google sometimes return special characters so I tried doing the encodeURI(string) first before storing to database. However, it includes the spaces when encoding so it makes it difficult to read the values in the database.

enter image description here

As you can see, the spaces in some rows are also encoded as %20. How can identify which strings have special characters so only those rows will be encoded and the other rows using the same alphabet will remain the same? Is there any efficient approach to that?

Edited on March 10, 2014: This is what I just did to solve this:

$unreadable_characters = array("%20", "%27", "%2E", "%2C", "_");
    $readable_characters = array(" ", "'", ".", ",", " ");

//and then use str_replace to change all those characters to their readable formats:

$keyword = str_replace($unreadable_characters, $readable_characters, $value[0]);

Using urldecode() when retrieving values from database still outputs the correct strings in the UI :)

Upvotes: 3

Views: 2153

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172388

I think you can use a regex to check the alphabets:

var st = $('#id').val();
if(/^[a-zA-Z0-9- ]*$/.test(st) == false) {
    alert('string contains non english characters');
}

Upvotes: 7

Related Questions