Sheldon
Sheldon

Reputation: 276

Remove part of String in JavaScript

I have a String like

var str = "test\ntesttest\ntest\nstringtest\n..."

If I reached a configured count of lines ('\n') in the string, I want to remove the first line. That means all text to the first '\n'.

Before:

var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"

After:

var str = "testtest2\ntest3\nstringtest4\n...5"

Is there a function in Javascript that I can use?

Thanks for help!

Upvotes: 0

Views: 4924

Answers (5)

alishad
alishad

Reputation: 139

You could use the substring(..) function. It is built-in with JavaScript. From the docs:

The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.

Usage:

mystring.substring(start,end)

The start index is required, the end index is not. If you omit the end index, it will substring from the start to the end of the string.

Or in your case, something like:

str = str.substring(str.indexOf('\n')+1);

Upvotes: 0

user3104423
user3104423

Reputation:

You could write a function like this if I understand you correctly

function removePart(str, count) {  
    var strCount = str.split('\n').length - 1;
    if(count > strCount) {   
        var firstIndex = str.indexOf('\n');
        return str.substring(firstIndex, str.length -1);
    }
    return str;
}

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You could use string.replace function also.

> var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
> str.replace(/.*\n/, '')
'testtest2\ntest3\nstringtest4\n...5'

Upvotes: 1

Nils O
Nils O

Reputation: 1321

str.substr(str.indexOf("\n")+1)

str.indexOf("\n")+1 gets the index of the first character after your first linebreak. str.substr(str.indexOf("\n")+1) gets a substring of str starting at this index

Upvotes: 0

leopik
leopik

Reputation: 2351

Find the first occurence of \n and return only everything after it

var newString = str.substring(str.indexOf("\n") + 1);

The + 1 means that you're also removing the new-line character so that the beginning of the new string is only text after the first \n from the original string.

Upvotes: 3

Related Questions