Micheal
Micheal

Reputation: 81

replace in javascript to cut off part of string

I have this string, how can I make it until .html?

string

https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1

make it into

https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html

Upvotes: 0

Views: 58

Answers (4)

this is yash
this is yash

Reputation: 533

This works fine according to your requirment

let url = "https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable- 
         battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1"


url.substring(0, <nbsp> url.indexOf('.html')<nbsp> + <nbsp>5)

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

Maybe you're looking for something like this example:

var str = 'https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1';

console.log(str.match('^.+\.html')[0]);

I've used regex with the pattern ^.+\.html to match the url. The regex means: From the beginning of the string to .html


If you want to split the url to 2 parts, you could try:

var str = 'https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1';

var parts = str.split(/\?/);

console.log(parts[0]);
console.log('?' + parts[1]);

Upvotes: 3

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

You can use String.prototype.split()

var url =  "https://www.lazada.com.ph/products/fujitsu-standard-aa-rechargeable-battery-2000mah-4pcs-i237968048-s311807989.html?spm=a2o4k.searchlist.list.47.7f1a484d4gpCFd&search=1";


console.log(url.split('?', 1)[0])

Upvotes: 1

Bergi
Bergi

Reputation: 664599

You can use the URL API:

var url = new URL(string);
url.search = "";
url.hash = "";
return url.href;

Upvotes: 0

Related Questions