Pregunta

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.

¿Fue útil?

Solución

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);
} 

Otros consejos

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"

How about something like this:

function truncateAfter(original, pattern) {
  return original.substring(0, original.indexOf(pattern) + pattern.length);
}

What this does is find the first index of the pattern you're looking for, and return a substring of the original string that starts at the beginning and ends after the first instance of the pattern.

Example Usage:

truncateAfter('dabcdefghi', 'abc');
>> 'dabc'

If instead you want to truncate the output before and after the pattern you're looking for, would just checking if the pattern is in the string and then using the pattern as the output be what you're looking for?

function truncate(original, pattern) {
  if (original.indexOf(pattern) != -1) {
    return pattern;
  }
}

Example Usage:

truncate('dabcdefghi', 'abc');
>> 'abc'

Please see the below code:

var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc")+3, str1.length);

alert(str2);

You were correct but one thing you missed is doing +3 in the indexOf. the indexOf("abc") would return 0 which in turn will give you thw whole string again.

Or check out this fiddle link:

Working Fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top