0

I am trying to concatenate an "http://" to the variable 'bar' if it does not already exist, before sending it to ajax where it will be added to the database and will also be displayed back on the page. I can do this in PHP in the processing script and have it added to the db but that does not put it back on the page (without a refresh).

$('#update').click(function() {
    var foo     = "http://";
    var bar     = $('#url').val();

    if (bar != '') {
        if (!preg_match('#^[a-zA-Z]+://#', bar)) {
            var bar = foo.concat(bar);
        }
    }

    $.ajax({
        url         : 'update_this.php',
        method      : 'post',
        data        : {bar:bar},
        success : function(response) {
            $('#id').children('a[data-target=x]').attr('href',bar);

        }
    });
});
LyleCrumbstorm
  • 171
  • 1
  • 12

1 Answers1

1

preg_match doesn't exist in JavaScript but it does offer regular expression functionality. See for example this stackoverflow question and its answer: How can I use preg_match in jQuery?.

So, a possibility would be to use the match(regExp) function that operates on a string.

What's more, '#^[a-zA-Z]+://#' is not a valid regular expression for Javascript. If you want to use a JavaScript regular expression literal you need to change two things:

  • Don't use ', i.e. don't format the expression as a string.
  • # is not a valid delimiter for a regular expression. Use / instead. Also keep in mind that you then have to escape the / at the end of your expression.

So the resulting expression would then be: /^[a-zA-Z]+:\/\//.

Alternatively, you could use a RegExp object. See here for an introduction: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

Last but not least, I want to point out that this regular expression would actually also match wrong formats, e.g. htpts://. If this is a concern, you could use groups to check if the match is either equal to https:// or http:// and replace it if necessary.

zubi
  • 26
  • 4