Javascript: Removing first text line if string starts with certain characters - javascript

I wrote a script for some text manipulation, and want to add a function so that the first line of my input string is removed if it starts with the symbol '>'. I tried to find a solution for hours now, but I cannot get it to work: Somehow the first line is not removed properly.
My input text should be processed as it is if it looks like this:
"HABHHIKKLLMMNMNIL"
and the first line should be removed if it looks like this:
"
>some text
HABHHIKKLLMMNMNIL
"
My current solution would look like this:
// remove first line if starts with '>'
if (sequence_str.substring(0) === '>'){
// break the textblock into an array of lines
var lines = sequence_str.split('\n');
// remove one line, starting at the first position
lines.splice(0,1);
// join the array back into a single string
var sequence_str = lines.join('\n');
}
sequence_str = sequence_str.replace(/(\r\n|\n|\r)/gm,""); //remove linebreaks
I would appreciate any ideas, and I hope some could help me to figure out where the problem is.
Thanks!

Why not just this?
sequence_str = sequence_str.replace(/^>.*/,'');
This will remove the first line if it starts with >. It will leave an empty line (the newline character is unaffected), but since you're later stripping all line-breaks, it doesn't matter.

just try this
"lines = lines.splice(0,1);"
instead of "lines.splice(0,1);"

Thank you so much, I really like the short codes you suggested.
The error was that I used
if (sequence_str.substring(0) === '>')
where it should be
if (sequence_str.substring(0,1) === '>')
I am a JavaScript beginner and come from the Python corner, please excuse my stupid mistake
EDIT:
If someone is interested to see how the end product looks like:
http://bluewoodtree.zxq.net/crop_and_cleave.html

Related

Line break javascript doesn't insert new line "\n"

I've been trying to wrap my head around this whole line break thing, and I've searched and researched my soul out here. I can't seem to find an answer to my specific problem here. I want to fetch the input from a textarea and put it in an array with new lines. All it does is put a comma between the words, and it seems it only adds multiple commas to where the line breaks are supposed to be. When I add < br / >, all it does is exclude the letter b from the text.
function Wordscount() {
var pText = document.getElementById("myTextarea").value.split(/[\n <>.,\?]/);
document.getElementById("text").innerHTML = pText;
It basically just looks like this when I test it :
I am new to Javascript, and I wouldn't have gone for this solution unless this was the method our professor told us to use. I'm really frustrated here, and I'm just trying to get the hang of this.
Splitting a string turns it into an array. Treating an array as a string is equivalent to calling yourArray.join(','). Since you don't want to add commas, don't just treat the array as a string.
If you want to put HTML line breaks in, then you need to do so explicitly.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
var string_of_html = array_of_lines.join("<br>");
document.getElementById("text").innerHTML = string_of_html;
If you don't want HTML special characters to be treated as having special meaning, then convert each line to a text node and append it instead.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
document.getElementById("text").innerHTML = "";
while(var text = array_of_lines.unshift()) {
document.getElementById("text").appendChild(
document.createTextNode(text)
);
document.getElementById("text").appendChild(
document.createElement("br")
);
}

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

How remove a line of a string in Java Script

I would like to remove a specific line of a string using the replace.
If it is not possible with a replace, like some suggestion how i can delete a line, for example, my text have 3 lines, and i need remove line 2 or line 3... Why I can make this?
this is my first line and here this is my second line -> i need
delete this line here is another line
replace( "and here this is my second line", WHAT I NEED USE HERE TO REMOVE THIS LINE );
Solution is use splice first and join after remove line:
var str="this is my first line\nand here this is my second line -> i need delete this line\nhere is another line";
ar=str.split('\n'); ar.splice(1,1); str=ar.join('\n'); // This remove line 2
ar=str.split('\n'); ar.splice(2,1); str=ar.join('\n'); // This remove line 3
console.log(str);
Given that
var text = "";
text += "this is my first line\n";
text += "and here this is my second line\n";
text += "here is another line\n";
If you need to remove the first occurrence of the string use this:
text = text.replace("and here this is my second line\n", '');
And if you need to remove all the occurrences of the string use this one:
text = text.replace(/and here this is my second line\n/g, '');
Take into account that in the second example regular expression are used.
\n is the special character for line breaks and might be in different positions in your specific code
You can simply remove the line by replacing the target line with an empty string.
$(.someDivClass).text().replace("text to replace", "");
However I don't think it would completely remove the element containing that text, if that's what you're looking for.
With standard JS, you use this snippet in a method and make some action trigger that event such as a button click:
if(document.getElementById("id of <p> tag").innerHTML == "specific text")
document.getElementById("id of <p> tag").innerHTML = '';
I am not sure what your intentions are with removing the text and whether or not you want to completely remove the element containing the text, so this is the best solution I can offer. If you explain what your intentions are and how it will be applied to your project, I can provide a better solution.

Change Multi line strings to Single line

Hi I have some text in following format,
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545 etc....
Each line break'ed into next line with "Enter". I have nearly 2000 lines of text like this. i want o display the above string to a single line like this.
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545,
686672,
683545 etc..
I think there is some tweak options in CSS for doing this. Is there a way in JavaScript to do this? Actually it is not a requirement for me, am just curious to know how it is done.
Edit:
In My text editor it looks like this,
When i try to run it, this is what i get.
Thats why i want to remove the enter, multiline.......
You can use Regular expression to remove all the linebreaks and replace them using space.
str = str.replace(/\n/g, ' ');
Here, \n will match all the line-breaks, and replace them by space
I have a simple way for this. You can do this without extra code. Just write like this -
var str = "12345,\
234234,\
234324,\
234324,\
234324,\
234234";
now just add a slash
Ok, If you don't want to use the above method then use another plan is -
take inside an array and after that use the join method
var str = [12345,
234234,
234324,
234324,
234324,
234234];
str.join(",");
If we are using ES6, Then we have an elegant way to do this using Backtick -
var str = `12345,
234234,
234324,
234324,
234324,
234234`;
Since your data is already comma separated, you can try to add "[" to the beginning and append " ].toString().replace(/\n/g," ") " to the end of your data to get a single line string like this:
[683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545].toString().replace(/\\n/g," ")
then you get:
"683101,682303,682302,682315,683581,686667,682008,683572,683573,682313,686672,683545"
I hope this helps :)
If all you want is to put those values in one line then, you can set those values as the value of a textarea field. This will allow you to read all those values into a javascript string. Afterward you can apply the regular expression that Tushar suggested.
See the code segment below:
<textarea id="content">
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545
</textarea>
Here is the javascript:
var content = $('#content').val();
var content = content.replace(/\n/g, ' ');
console.log(content);

Trying to use Javascript regex to grab a section of "&" delimited text whether or not it's the last value

My text looks similar to this:
action=addItem&siteId=4&lang_locale=en_US&country=US&catalogId=1&productId=417689&displaySize=7&skuSize=2194171&qty=1&pil=7&psh=had+AIRJRnjbp7+rGivIKg00
and I want to replace the value of 'psh'. It may sometimes not be the last value (it may be followed by &something=else).
I've tried doing these lines of code:
var text = text.replace(/&psh=.*(?=&|$)/, "&psh=" + data.psh);
var text = text.replace(/&psh=.*(?=[&|$]+)/, "&psh=" + data.psh);
var text = text.replace(/(?:&psh=)(.*)(?=[&|$]+)/, data.psh);
None of them work for both situations. Use this site to check regexes.
This should work:
var text = text.replace(/&psh=[^&]*/, "&psh=" + data.psh);
[^&]* matches a string of any length that consists of any characters except &, therefore the match will continue until the end of the string or until (but not including) the next &, whichever comes first.
Tim's answer may work, but I fear it is not the best possible answer. The string you are giving as an example looks a lot like a url. If it is, that means there can sometimes be a pound sign in it as well (#). To compensate for that you actually need to modify your code to look like this:
var text = text.replace(/&psh=[^&#]*/, "&psh=" + data.psh);
Notice the # which was added in order to not get tripped up by anchor tags in the url.

Categories

Resources