Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncating a string after and before a word in javascript

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.

like image 797
user2882721 Avatar asked Jan 24 '14 06:01

user2882721


People also ask

How do you remove all characters from a string after a specific character in JavaScript?

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.

How do you cut a string before?

Using str. partition() to get the part of a string before the first occurrence of a specific character. String partition() method return tuple.

How do you shorten a string in JavaScript?

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 &hellip; (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str.


2 Answers

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);
} 
like image 141
hemanth Avatar answered Oct 10 '22 03:10

hemanth


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"
like image 6
avetisk Avatar answered Oct 10 '22 03:10

avetisk