Remove weird characters using jquery/javascript

淺唱寂寞╮ 提交于 2021-02-19 05:05:36

问题


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("‘", "");
  }

回答1:


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("’","");



回答2:


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 common characters (accents, other alphabets, less common 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.




回答3:


This code works fine for me:

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



回答4:


Created a fiddle for your problem solution

Code Snippet:

var str = "‘Some string hereâ€";
str = str.replace("‘", "");
str = str.replace("â€", "");
alert(str);



回答5:


.filter('SpecialCharacterToSingleQuote', function() {
        return function(text) {
            return text ? String(text).replace(/â/g, "'").replace(/&#128;|&#153;|&#156;|&#157;/g, "") : '';
        };
    });


来源:https://stackoverflow.com/questions/24629467/remove-weird-characters-using-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!