How to remove specific word from string?

Asked

Viewed 414 times

3

I have an input where the user can enter the site itself, and insert http:// when writing to db, but I would like to treat so that if there is already this tag in the input it does not enter again, because qnd the user updates it enters again the tag and it is http://http://

3 answers

4

You can do it like this:

let url = "https://google.com";

let novaUrl = url.replace(/^https?:\/\//, '');

console.log(novaUrl);

4

A simple replace works.

You could also use a regex in replace to remove both "http://" and "https://".

let input = 'http://answall.com';
input = input.replace('http://', '');

console.log(input);

let input2 = 'https://answall.com';
input2 = input2.replace(/^https?:\/\//,'', '');

console.log(input2);

2


You can use index:

let uri = 'meusite.com'

// -1 é não encontrado
if (uri.indexOf('http://') == -1 && uri.indexOf('https://') == -1){
   uri = 'http://' + uri;
}
  • 1

    I think this is the best answer not to insert http if the input already has. But I think you should check https also. +1

  • 1

    I managed to do what I needed here, it worked out, quarrel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.