Home > Software design >  I have an string and i want to delete from a specific character to the end of the string in JavaScri
I have an string and i want to delete from a specific character to the end of the string in JavaScri

Time:02-14

i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].

How can i do this?

CodePudding user response:

You van try something like:

console.log("someRandomText&ab_channel=thisPartCanChange".split("&")[0])

CodePudding user response:

const yourString = 'SomeRandomText&ab_channel=thisPartCanChange'
console.log(yourString.split('&ab_channel')[0])

CodePudding user response:

I would do a regex replacement on &.*$ and replace with empty string.

var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));

Note that the above approach is robust with regard to strings which don't even have a & component.

CodePudding user response:

You can use substring which extract the characters between two specified index without changing the original string

const yourString = 'someRandomText&ab_channel=thisPartCanChange';
const newStr = yourString.substring(0, yourString.indexOf('&'));
console.log(newStr)

  • Related