Remove one line in txt file ( NODE.js) - javascript

I make a text file "foo\nbar\nbas"
When i append coke(with adding \n), then the file will be "foo\nbar\nbas\ncoke"
I want to remove the foo.
Help me!

Fo your use case that you have provided, a simple answer is split on \n, remove the first item, add the new item to the end, and join the array to form your new string.
var parts = "foo\nbar\nbas".split("\n").slice(1);
parts.push("coke");
var updated = parts.join("\n");
Other option is to use indexOf to find the first occurrence of \n and substring to select the portion of the string, then it is a simple concatenation.
var str = "foo\nbar\nbas";
var position = str.indexOf("\n")+1;
var updated = str.substring(position) + "\ncoke";

You can use simple string manipulation if your task is not complicated by further constraints. Such is as follows:
var fileContents = "foo\nbar\nbas";
// Read Text File, in this case, I have set it.
fileContents = fileContents.replace("foo\n", "");
fileContents += "\ncoke";
// Write back to file

Related

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

How to find a substring only in the text portion of an HTML string, with Javascript?

UPDATE: I am no longer specifically in need of the answer to this question - I was able to solve the (larger) problem I had in an entirely different way (see my comment). However, I'll check in occasionally, and if a viable answer arrives, I'll accept it. (It may take a week or three, though, as I'm only here sporadically.)
I have a string. It may or may not have HTML tags in it. So, it could be:
'This is my unspanned string'
or it could be:
'<span class="someclass">This is my spanned string</span>'
or:
'<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>'
or:
'<span class="no-text"><span class="silly-example"></span></span><span class="some-class">This is my spanned string</span>'
I want to find the index of a substring, but only in the portion of the string that, if the string were turned into a DOM element, would be (a) TEXT node(s). In the example, only in the part of the string that has the plain text This is my string.
However, I need the location of the substring in the whole string, not only in the plain text portion.
So, if I'm searching for "span" in each of the strings above:
searching the first one will return 13 (0-based),
searching the second will skip the opening span tag in the string and return 35 for the string span in the word spanned
searching the third will skip the empty span tag and the openings of the two nested span tags, and return 91
searching the fourth will skip the nested span tags and the opening of the second span tag, and return 100
I don't want to remove any of the HTML tags, I just don't want them included in the search.
I'm aware that attempting to use regex is almost certainly a bad idea, probably even for simplistic strings as my code will be encountering, so please refrain from suggesting it.
I'm guessing I will need to use an HTML parser (something I've never done before). Is there one with which I can access the original parsed strings (or at least their lengths) for each node?
Might there be a simpler solution than that?
I did search around and wasn't been able to find anyone ask this particular question before, so if someone knows of something I missed, I apologize for faulty search skills.
The search could loop through the string char by char. If inside a tag, skip the tag, search the string only outside tags and remember partial match in case the text is matched partially then interrupted with another tag, continue the search outside the tag.
Here is a little function I came up with:
function customSearch(haysack,needle){
var start = 0;
var a = haysack.indexOf(needle,start);
var b = haysack.indexOf('<',start);
while(b < a && b != -1){
start = haysack.indexOf('>',b) + 1;
a = haysack.indexOf(needle,start);
b = haysack.indexOf('<',start);
}
return a;
}
It returns the results you expected based in your examples. Here is a JSFiddle where the results are logged in the console.
Let's start with your third example:
var desiredSubString = 'span';
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
Remove all HTML elements from entireString, above, to establish textString:
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
You can then find the index of the start of the textString within the entireString:
var indexOfTextString = entireString.indexOf(textString);
Then you can find the index of the start of the substring you're looking for within the textString:
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
Finally you can add indexOfTextString and indexOfSubStringWithinTextString together:
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
Putting it all together:
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var desiredSubString = 'span';
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
var indexOfTextString = entireString.indexOf(textString);
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
You could use the browser's own HTML parser and XPath engine to search only inside the text nodes and do whatever processing you need.
Here's a partial solution:
var haystack = ' <span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var needle = 'span';
var elt = document.createElement('elt');
elt.innerHTML = haystack;
var iter = document.evaluate('.//text()[contains(., "' + needle + '")]', elt).iterateNext();
if (iter) {
var position = iter.textContent.indexOf(needle);
var range = document.createRange();
range.setStart(iter, position);
range.setEnd(iter, position + needle.length);
// At this point, range points at the first occurence of `needle`
// in `haystack`. You can now delete it, replace it with something
// else, and so on, and after that, set your original string to the
// innerHTML of the document fragment representing the range.
console.log(range);
}
JSFiddle.

how to replace part of part of string in javascript

I have two GUIDs. I am looking for to replace c013d94e from 1st guid with cd11d94e of second guid in Javascipt.
I checked javascript replace() method but not sure how i can use it with my specific case.
c013d94e-3210-e511-82ec-303a64efb676 - 1st Guid
cd11d94e-3210-e511-82ec-303a64efb676 - 2nd Guid
Following is my code where i am trying to do it
for(var i=0; i < response[1].length;i++)
angular.forEach($scope.studentPermissions[i][0].Children, function (subject) {
string 1stGuid= response[1].data[i].Id; // it contains cd11d94e-3210-e511-82ec-303a64efb676
subject.Id = // it contains c013d94e-3210-e511-82ec-303a64efb676
});
replace takes 2 parameters, the first is the string to search for and the second is the replacement string. It doesn't modify the original string, it simply returns a new string with the value replaced.
You can perform your replace like this:
var guid = 'c013d94e-3210-e511-82ec-303a64efb676';
guid = guid.replace('c013d94e', 'cd11d94e');
console.log(guid); // 'cd11d94e-3210-e511-82ec-303a64efb676'
#Jamen. Yes the other part of 1st string will always be same. How can i use concatenate?
You don't even need to use replace then? Just make a brand new string:
var guid = "cd11d94e-3210-e511-82ec-303a64efb676";
But, to actually answer the question in the title:
var input = "c013d94e-3210-e511-82ec-303a64efb676";
var output = input.replace("c013d94e", "cd11d94e");
console.log(output); // cd11d94e-3210-e511-82ec-303a64efb676
But like I said, in your situation this shouldn't be necessary, based on the quote.

How to retrieve a word from the string

str = COUPONS
how to get the word COUPONS from the str. the word #homecoupon might change to other word so i can't do the substring method of retrieving the nth position value. the class ="current">COUPONS</a> will always be fixed.
Is there a way i can back track and retrieve the last nth word.
The best way to parse HTML in the browser is to let the browser do it for you.
Create a dummy element in memory, then set its innerHTML to your string. You can then use the regular DOM API to find the text of that anchor element:
var div = document.createElement('div');
div.innerHTML = str;
var word = div.firstChild.textContent;
Here's the fiddle: http://jsfiddle.net/mREFu/
If you still have to support IE < 9, you'll have to use this:
var word = div.firstChild.textContent || div.firstChild.innerText;
Or you could get the text from the text node:
var word = div.firstChild.childNodes[0].nodeValue;
If it's an actual string not a part of a web page :
var str = 'COUPONS';
var word = str.match(/"current">(.*?)</);
if(word) word = word[1]; //== COUPONS
Or if you're using jQuery and that's an actual web page you can go :
$('a.current').each(function(){
alert($(this).text());
});
Using substring() and indexof() you can do this.
str = 'COUPONS';
// get rid of </a> assuming the string always ends with it
var x = str.substring(0,str.length-4);
// use the fixed part to get the value you want
alert(x.substring(x.indexOf('class ="current">')+17))
OR
str = 'COUPONS';
fixedPart = 'class ="current">';
// use the fixed part to get the value you want assuming str always ends with </a>
alert(str.substring(str.indexOf(fixedPart)+fixedPart.length, str.length-4))

Array.shift() and modify value in a single line?

This Javascript code removes the first file name from a file list and then removes its extension:
var fileNoExt = filelist.shift();
fileNoExt = fileNoExt.substr(0, fileNoExt.lastIndexOf('.'));
I'm curious - is it possible to turn this code into a one-liner?
How about using a regex?
If you want to enforce an extension after the ., use
var fileNoExt = filelist.shift().replace(/\.[^.]+$/, '');
otherwise, use
var fileNoExt = filelist.shift().replace(/\.[^.]*$/, '');
The second one matches my_crazy_file. and my_crazy_file.extension while the first only matches my_crazy_file.extension.
Here's a one-liner:
var filelist = ['file.name.ext', 'some.another.string']
filelist.shift().split('.').slice(0, -1).join('.') // 'file.name'
"is it possible to turn this code into a one-liner?"
Yes,
var fileNoExt = filelist[0].substr(0, filelist.shift().lastIndexOf('.'));
but why? It's clearer on two lines.

Categories