Categories
JavaScript Answers

How to Split a String Once in JavaScript?

To split a string once in our JavaScript code, we can use the JavaScript string’s indexOf method with the JavaScript string’s slice method to find the index of the first instance of the separator and then do the slicing.

For instance, we can write:

const s = "1|Ceci n'est pas une pipe: | Oui";
const i = s.indexOf('|');
const splits = [s.slice(0, i), s.slice(i + 1)];
console.log(splits)

We have the s string that we want to split by the first | .

Then we call indexOf with '|' to get the index of the first instance of the | symbol.

Next, we call slice with 0 and i to get the substring before the first | .

And likewise, we call slice with i + 1 to get the part after the first | .

We then put both substrings into the splits array.

Therefore, splits is:

["1", "Ceci n'est pas une pipe: | Oui"]
Categories
JavaScript Answers

How to Test if a URL String is Absolute or Relative with JavaScript?

To test if a URL string is absolute or relative with JavaScript, we can use a regex to do the check.

For instance, we can write:

const r = new RegExp('^(?:[a-z]+:)?//', 'i');
console.log(r.test('http://example.com'));
console.log(r.test('HTTP://EXAMPLE.COM'));
console.log(r.test('ftp://example.com/file.txt'));
console.log(r.test('//cdn.example.com/lib.js'));
console.log(r.test('test'));

We create the regex with the ^(?:[a-z]+:)?//’ pattern to check if the URL starts something with :// after it and more path segments appended after that.

The part before :// is optional for a URL to be considered absolute.

Then we use the test method to check if each URL is absolute or relative.

If it’s absolute, test returns true . Otherwise, it returns false .

Therefore, the first 4 console logs logs true and the last one logs false .

Categories
JavaScript Answers

How to Display a Loading Indicator When Making an Ajax Request with jQuery?

To display a loading indicator when making an Ajax request with jQuery, we can use the ajaxSetup method to show and hide the loading indicator before the request starts and when it finishes respectively.

For instance, we can add the loading indicator by writing:

<div id='loading'>
  loading
</div>

Then we can call the ajaxSetup method and then make the request by writing:

$.ajaxSetup({
  beforeSend: () => {
    $("#loading").show();
  },
  complete: () => {
    $("#loading").hide();
  }
});

$.ajax({
  type: 'GET',
  url: 'https://yesno.wtf/api',
})

We call ajaxSetup to add code that runs with all Ajax request made with ajax unless we specify otherwise.

beforeSend is run before the request is made, so we call $(“#loading”).show(); to show the loading indicator.

complete is run before the request is made, so we call $(“#loading”).hide(); to hide the loading indicator.

Then when we call ajax to make the Ajax request, we see the loading indicator shown and then hidden.

Categories
JavaScript Answers

How to Tell setInterval to Only Fire x Amount of Times with JavaScript?

To tell setInterval to only fire x amount of times with JavaScript, we can keep track of the number of times the setInterval callback is called.

Then when the limit is reached, we can call clearInterval to stop the setInterval timer.

For instance, we can write:

let x = 0;  
const intervalID = setInterval(() => {  
  if (++x === 5) {  
    window.clearInterval(intervalID);  
  }  
  console.log('hello')  
}, 200);

to keep track of the number of times the setInterval callback is called with x .

Then we call setInterval with a callback that increments x with ++ in front to return the value of x after incrementing by 1.

Next, we check if x is 5 to top the timer with clearInterval when the setInterval callback has been called 5 times.

clearInterval is called with the intervalID to stop the timer.

And then we call console log to log some message.

200 is the number of milliseconds between each setInterval call.

As a result, the setInterval callback will be called 5 times only.

Categories
JavaScript Answers

How to Disable the Submit Button on Form Submission with JavaScript and jQuery?

To disable submit button on form submission with JavaScript and jQuery, we can listen to the submit event of the form.

Then we can set the disabled attribute of the submit button to true when we submit the form.

For instance, if we have the following HTML form:

<form>
  <input>
  <input type='submit'>
</form>

Then we can write the following JavaScript to disable the submit button when we submit the form with jQuery by writing:

$('form').submit(function() {
  $(this).find(':input[type=submit]').prop('disabled', true);
});

We get the form with $(‘form’) .

Then we call submit on it with a callback to listen to the submit event of the form.

The callback we pass into submit get the submit button of the form with $(this).find(‘:input[type=submit]’) .

Then we call prop with 'disabled' and true to disable the form’s submit button.