urlencode() from PHP in JavaScript?


urlencode() from PHP in JavaScript?

我正在寻找类似的功能urlencode()从PHP只是在JavaScript。jQuery库

基本上,我需要编码字符串,然后用JavaScript将用户重定向到另一个页面。

没有完全匹配urlencode()的函数,但有一个完全等价于rawurlencode()的函数:encodeURIComponent()

用法:var encoded = encodeURIComponent(str);

你可以在这里找到参考:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

我的代码是JS函数相当于PHP的urlencode(基于PHP的源代码)

function urlencode(str) {
  let newStr = '';
  const len = str.length;
  for (let i = 0; i < len; i++) {
    let c = str.charAt(i);
    let code = str.charCodeAt(i);
    // Spaces
    if (c === ' ') {
      newStr += '+';
    }
    // Non-alphanumeric characters except "-", "_", and "."
    else if ((code < 48 && code !== 45 && code !== 46) ||
             (code < 65 && code > 57) ||
             (code > 90 && code < 97 && code !== 95) ||
             (code > 122)) {
      newStr += '%' + code.toString(16);
    }
    // Alphanumeric characters
    else {
      newStr += c;
    }
  }
  return newStr;
}

JS函数相当于PHP的urldecode.

function urldecode(str) {
  let newStr = '';
  const len = str.length;
  for (let i = 0; i < len; i++) {
    let c = str.charAt(i);
    if (c === '+') {
      newStr += ' ';
    }
    else if (c === '%') {
      const hex = str.substr(i + 1, 2);
      const code = parseInt(hex, 16);
      newStr += String.fromCharCode(code);
      i += 2;
    }
    else {
      newStr += c;
    }
  }
  return newStr;
}

如果你正在寻找一个相当于PHP的JS函数,可以看看phpjs.org:

http://phpjs.org/functions/urlencode: 573

这里你可以使用encodeURIComponent()(稍作修改)

From: https://www.php.net/manual/en/function.urlencode.php

返回一个字符串,其中除-_以外的所有非字母数字字符。已被替换为百分号(%)后面跟着两个十六进制数字空格编码为加号。它的编码方式与从WWW表单发布的数据被编码,这是相同的方式Application/x-www-form-urlencoded媒体类型。这与»不同RFC 3986编码(参见rawurlencode()),由于历史原因,空格被编码为加号

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent:

encodeuriccomponent()转义所有字符,除了:
未逃脱:A-Z -z 0-9 - _。! ~ * ' ()

在该页面的底部提供了一个代码片段,看起来像这样:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

我稍微调整了一下提供的javascript片段,以包含更多的字符。

我代码:

function urlEncodeLikePHP(str) {
    return encodeURIComponent(str).replace(/[.!~*'()]/g, function(c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
}

用法:

urlEncodeLikePHP("._!_~_*_'_(_)-''-&-|-/");
// effectively: "._!_~_*_'_(_)-'-&-|-/"

编码输出:

%2e_%21_%7e_%2a_%27_%28_%29-%5C-%26-%7C

encodeuriccomponent ()
http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp

试试urlencode from http://locutus.io/php/url/urlencode/。