Remove part of String in JavaScript - 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!

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.

You could use string.replace function also.
> var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
> str.replace(/.*\n/, '')
'testtest2\ntest3\nstringtest4\n...5'

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

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

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

Related

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

Replace last character of string using JavaScript

I have a very small query. I tried using concat, charAt, slice and whatnot but I didn't get how to do it.
Here is my string:
var str1 = "Notion,Data,Identity,"
I want to replace the last , with a . it should look like this.
var str1 = "Notion,Data,Identity."
Can someone let me know how to achieve this?
You can do it with regex easily,
var str1 = "Notion,Data,Identity,".replace(/.$/,".")
.$ will match any character at the end of a string.
You can remove the last N characters of a string by using .slice(0, -N), and concatenate the new ending with +.
var str1 = "Notion,Data,Identity,";
var str2 = str1.slice(0, -1) + '.';
console.log(str2);
Notion,Data,Identity.
Negative arguments to slice represents offsets from the end of the string, instead of the beginning, so in this case we're asking for the slice of the string from the beginning to one-character-from-the-end.
This isn't elegant but it's reusable.
term(str, char)
str: string needing proper termination
char: character to terminate string with
var str1 = "Notion,Data,Identity,";
function term(str, char) {
var xStr = str.substring(0, str.length - 1);
return xStr + char;
}
console.log(term(str1,'.'))
You can use simple regular expression
var str1 = "Notion,Data,Identity,"
str1.replace(/,$/,".")

Replace strings from left until the first occuring string in Javascript

I am trying to figure out how to replace example:
sw1_code1_number1_jpg --> code1_number1_jpg
hon2_noncode_number2_jpg --> noncode_number2_jpg
ccc3_etccode_number3_jpg --> etccode_number3_jpg
ddd4_varcode_number4_jpg --> varcode_number4_jpg
So the results are all string after the first _
If it doesn't find any _ then do nothing.
I know how to find and replace strings, str.replace, indexof, lastindexof but dont know how remove up to the first found occurrence.
Thank You
Use the replace method with a regular expression:
"sw1_code1_number1_jpg".replace(/^.*?_/, "");
You could split your string and get a slice
var str = 'sw1_code1_number1_jpg';
var finalStr = str.split('_').slice(1).join('_') || str;
If your original string does not contain an underscore, then it returns the original string.
UPDATE A simpler one with slice (still works with strings not containing underscores)
var str = 'sw1_code1_number1_jpg';
var finalStr = str.slice(str.indexOf('_') + 1);
This one works in all cases because when no underscore is found, -1 is returned and as we add 1 to the index we call str.slice(0) which is equal to str.
There are several approaches you can take:
var str = 'sw1_code1_number1_jpg';
var arr = str.split('_');
arr.shift();
var newSfr = arr.join('_');
Or you could use slice or replace:
var str = 'sw1_code1_number1_jpg';
var newStr = str.slice(str.indexOf('_')+1);
Or
var newStr = 'sw1_code1_number1_jpg'.replace(/^[^_]+_/,'');

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

What is the correct pattern for splitting a string in javascript, leaving just a-z words

I have the next code that was given to me to split up a string into an array.
var chk = str.split(/[^a-z']+/i);
The problem I'm having with this solution is that if the string has a period in the end, it's being replaced with ","
For example:
If I have the next string: "hi,all-I'm-glad."
The solution above results: "hi,all,I'm,glad," (notice the "," in the end).
I need that the new string will be: "hi,all,I'm,glad"
How can I acheive it ?
Check for a . being the last character and remove it first
var str = "hi,all-I'm-glad. that you, can help,me. that-doesn't make any-sense, I know.";
if(str.charAt( str.length-1 ) == ".") {
str = str.substring(0,str.length-1);
}
var chk = str.split(/[^a-z']+/i);
console.log(chk);
var chk = str.match(/[a-z']+/gi);
console.log(chk);
You could check to see if the last element of your string array returns an empty string and remove that element
if (chk[chk.length-1] == "")
{
chk.pop();
}
var chk="to.to.".split(/[^a-z']+/i); if(chk[chk.length-1].length==0){chk.pop()}; console.log(chk);
To remove the last value of your array using pop if this one is empty.
You can utilize the pure regex power:
"hi,all-I'm-glad. that you, can help,me. that-doesn't make any-sense, I know.".replace(/[\-\.\s]/g, ',').replace(/,{2,}/g, ',').replace(/,$/,'')

Categories

Resources