admin管理员组

文章数量:1352882

I have this string ‘Some string here’. I want to remove these weird characters(‘, ’) from this string. I am currently using replace() function but it does not replace it with empty string. Below is the script. How can I remove it?

  for (var i = 0, len = el.length; i < len; i++) {
      $(el[i]).text().replace("‘", "");
  }

I have this string ‘Some string here’. I want to remove these weird characters(‘, ’) from this string. I am currently using replace() function but it does not replace it with empty string. Below is the script. How can I remove it?

  for (var i = 0, len = el.length; i < len; i++) {
      $(el[i]).text().replace("‘", "");
  }
Share Improve this question asked Jul 8, 2014 at 10:28 26ph1926ph19 39310 silver badges23 bronze badges 2
  • Depending on your context and how many characters you want to replace. Would it not be easier to define allowed characters, and remove any that you didn't specify? – SubjectCurio Commented Jul 8, 2014 at 10:30
  • The problem is that these strings are generated automatically using some kind of software. I need to remove them using javascript – 26ph19 Commented Jul 8, 2014 at 10:32
Add a ment  | 

5 Answers 5

Reset to default 5

you have to just remove the elements whose ascii value is less then 127

var input="‘Some string here’.";
var output = "";
    for (var i=0; i<input.length; i++) {
        if (input.charCodeAt(i) <= 127) {
            output += input.charAt(i);
        }
    }
 alert(output);//Some string here.

fiddle link

OR

remove your loop and try

$(el[i]).text().replace("‘","").replace("’","");

Those weird characters probably aren't so weird; they're most likely a symptom of a character encoding problem. At a guess, they're smart quotes that aren't showing up correctly.

Rather than try to strip them out of your text, you should update your page so it displays as UTF-8. Add this in your page header:

<meta charset="utf-8" />

So why does this happen? Basically, most character encodings are the same for "simple" text - letters, numbers, some symbols - but have different representations for less mon characters (accents, other alphabets, less mon symbols, etc). When your browser gets a document without any indication of its character encoding, the browser will make a guess. Sometimes it gets it wrong, and you see weird characters like ‘ instead of what you expected.

This code works fine for me:

"‘Some string here’".replace("‘","").replace("’","");

Created a fiddle for your problem solution

Code Snippet:

var str = "‘Some string hereâ€";
str = str.replace("‘", "");
str = str.replace("â€", "");
alert(str);
.filter('SpecialCharacterToSingleQuote', function() {
        return function(text) {
            return text ? String(text).replace(/â/g, "'").replace(/&#128;|&#153;|&#156;|&#157;/g, "") : '';
        };
    });

本文标签: Remove weird characters using jqueryjavascriptStack Overflow