Home » Php » php – Use JavaScript to stripslashes ? possible

php – Use JavaScript to stripslashes ? possible

Posted by: admin July 12, 2020 Leave a comment


I’m using ajax to grab a URL. The problem is the URL has slashes in it and when the JQuery load takes place afterwords it will not load the page.

AJAX success bit:

success: function(data) {


echo json_encode( array('OPTpermalink'=>$OPTpermalink,));

AND the response


So need to strip the slashes. I know how to do it in PHP but not in AJAX JavaScript.

Any ideas?


How to&Answers:

A new answer to an old question:

String.prototype.stripSlashes = function(){
    return this.replace(/\(.)/mg, "$1");

Example of use:

var str = "You\'re slashed \/\..\/\"; // Text from server
str = str.stripSlashes() ;


You're slashed /\../\


There has been a good port of many of php’s core functions, including stripslashes over here: http://phpjs.org/functions/stripslashes/

function stripslashes (str) {
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +      fixed by: [email protected]
  // +   improved by: marrtins
  // +   bugfixed by: Onno Marsman
  // +   improved by: rezna
  // +   input by: Rick Waldron
  // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
  // +   input by: Brant Messenger (http://www.brantmessenger.com/)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: stripslashes('Kevin\'s code');
  // *     returns 1: "Kevin's code"
  // *     example 2: stripslashes('Kevin\\'s code');
  // *     returns 2: "Kevin\'s code"
  return (str + '').replace(/\(.?)/g, function (s, n1) {
    switch (n1) {
    case '\':
      return '\';
    case '0':
      return '\u0000';
    case '':
      return '';
      return n1;


This is an old post but thought I would add my answer, seems more efficient than some other answers here:

var url = "http:\/\/www.divethegap.com\/update\/options\/padi-open-water\/"

var res = url.replace(new RegExp("\\", "g"), "");

This will replace all occurrences of a backslash character with nothing.


You’re sending JSON, but inserting it directly into a HTML element. That is not wise, can create broken results, and probably not what you want to do in the first place.

You should probably either

  • change the PHP script’s output to create proper HTML

  • expect JSON on the JavaScript side (using jQuery’s dataType parameter, or the shorthand $.json(), and parse that


Have you tried string.replace?

success: function(data) {
 $('#OPTcontentpanel').load(data.OPTpermalink.replace("\", ""));