How do I truncate a string after or before a pattern?
Say if I have a string "abcdef"
I need to truncate everything after "abc"
so the output will be:
def
and if i say truncate before "def"
the output should be:
abc
Below is the code that I tried
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc"), str1.length);
console.log(str2);
I didn't get the output.
I'm stuck here any help will be much appreciated.
slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); . The slice method will return the part of the string before the specified character.
Using str. partition() to get the part of a string before the first occurrence of a specific character. String partition() method return tuple.
Essentially, you check the length of the given string. If it's longer than a given length n , clip it to length n ( substr or slice ) and add html entity … (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str.
You need to pass length of "abc" as the 2nd argument in substr method
var str1 = "abcdefgh";
var pattern = "abc";
var str2 = str1.substr(str1.indexOf(pattern), pattern.length); <-- check this line
console.log(str2);
However above code might return unexpected results for patterns which are not present in the string.
var str1 = "abcdefgh";
var pattern = "bcd";
var str2 = "";
if(str1.indexOf(pattern)>=0) //if a pattern is not present in the source string indexOf method returns -1
{
//to truncate everything before the pattern
//outputs "efgh"
str2 = str1.substr(str1.indexOf(pattern)+pattern.length, str1.length);
console.log("str2: "+str2);
// if you want to truncate everything after the pattern & pattern itself
//outputs "a"
str3 = str1.substr(0, str1.indexOf(pattern));
console.log("str3: "+str3);
}
var str = "sometextabcdefine";
var pattern = "abc";
var truncateBefore = function (str, pattern) {
return str.slice(str.indexOf(pattern) + pattern.length);
};
var truncateAfter = function (str, pattern) {
return str.slice(0, str.indexOf(pattern));
}
console.log(truncateBefore(str, pattern)); // "define"
console.log(truncateAfter(str, pattern)); // "sometext"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With