Is there a way in JavaScript to remove everything after last hyphen if its a number?
product-test-grid-2
So Result would be only:
product-test-grid
Trying to use this resource:
Remove everything after a certain character
You can use a simple regular expression with replace.
eg..
/-\d+$/ = a dash followed by 1 or more numbers \d+, that's at the end $
const reLast = /-\d+$/;
const test1 = 'product-test-grid-2';
const test2 = 'product-test-grid-nan';
console.log(test1.replace(reLast, ''));
console.log(test2.replace(reLast, ''));
Simple JS, No regex involved
const label = 'product-test-grid-2'.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
console.log(label.join('-'));
// you can encapsulate it into function
function formatLabel(label) {
label = label.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
return label.join('-');
}
// 2 should be removed at the end
console.log(formatLabel('product-test-grid-2'));
// two should be left untouched
console.log(formatLabel('product-test-grid-two'));
'product-test-grid-2'.replace(/(?<=-)\d*$/, '') will preserve the last hyphen.
'product-test-grid-2'.replace(/-\d*$/, '') will remove it.
Split by "-", check if last item is a number: pop if it is, join with "-":
sentence="product-test-grid-2";
words=sentence.split("-");
if(words[words.length-1].match(/^\d+$/)) words.pop();
result=words.join("-");
console.log(result);
You can do this with regrx but it seems to me Overkill
I would do that
const str='product-test-grid-2'
const pos=str.lastIndexOf('-')
const res=str.slice(0,pos)
console.log(res)
Related
How do I remove a character from a string and remove the previous character as well?
Example:
"ABCXDEXFGHXIJK"
I want to split the string by "X" and remove the previous character which returns
"ABDFGIJK" // CX, EX, HX are removed
I found this thread but it removes everything before rather than a specific amount of characters: How to remove part of a string before a ":" in javascript?
I can run a for loop but I was wondering if there was a better/simpler way to achieve this
const remove = function(str){
for(let i = 0; i < str.length; i++){
if(str[i] === "X") str = str.slice(0, i - 1) + str.slice(i + 1);
}
return str
}
console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK
You can use String.prototype.replace and regex.
"ABCXDEXFGHXIJK".replace(/.X/g, '')
The g at the end is to replace every occurrence of .X. You can use replaceAll as well, but it has less support.
"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')
If you want it to be case insensitive, use the i flag as well.
"ABCXDEXFGHXIJK".replace(/.x/gi, '')
The simplest way is to use a regular expression inside replace.
"ABCXDEXFGHXIJK".replace(/.X/g, "")
.X means "match the combination of X and any single character before it, g flag after the expression body repeats the process globally (instead of doing it once).
While not the most computationally efficient, you could use the following one-liner that may meet your definition of "a better/simpler way to achieve this":
const remove = str => str.split("X").map((ele, idx) => idx !== str.split("X").length - 1 ? ele.slice(0, ele.length - 1) : ele).join("");
console.log(remove("ABCXDEXFGHXIJK"));
Maybe you can use recursion.
function removeChar(str, char){
const index = str.indexOf(char);
if(index < 0) return str;
// removes 2 characters from string
return removeChar(str.split('').splice(index - 2, index).join());
}
Try this way (Descriptive comments are added in the below code snippet itself) :
// Input string
const str = "ABCXDEXFGHXIJK";
// split the input string based on 'X' and then remove the last item from each element by using String.slice() method.
const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1));
// Output by joining the modified array elements.
console.log(splittedStr.join(''))
By using RegEx :
// Input string
const str = "ABCXDEXFGHXIJK";
// Replace the input string by matching the 'X' and one character before that with an empty string.
const modifiedStr = str.replace(/.X/g, "")
// Output
console.log(modifiedStr)
I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))
I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));
I have an array contains names. Some of them starting with a dot (.), and some of them have dot in the middle or elsewhere. I need to remove all names only starting with dot. I seek help for a better way in JavaScript.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker';
var refinedArr = ??
You can use the filter function and you can access the first letter of every word using item[0]. You do need to split the string first.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker'.split(", ");
var refinedArr = myarr.filter(function(item) {
return item[0] != "."
});
console.log(refinedArr)
Use filter and startsWith:
let myarr = ['ad', 'ghost', 'hg', '.hi', 'jk'];
let res = myarr.filter(e => ! e.startsWith('.'));
console.log(res);
You can use the RegEx \B\.\w+,? ? and replace with an empty String.
\B matches a non word char
\. matches a dot
\w+ matches one or more word char
,? matches 0 or 1 ,
[space]? matches 0 or 1 [space]
Demo:
const regex = /\B\.\w+,? ?/g;
const str = `ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
I'm trying to extract a substring from a file with JavaScript Regex. Here is a slice from the file :
DATE:20091201T220000
SUMMARY:Dad's birthday
the field I want to extract is "Summary". Here is the approach:
extractSummary : function(iCalContent) {
/*
input : iCal file content
return : Event summary
*/
var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
return(arr);
}
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the * inside the parenthesis as
suggested above. Otherwise your matching
group will contain only one
character.
Get rid of the ^ and $. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.
I suppose you want the matching group (what's
inside the parenthesis) rather than
the full array? arr[0] is
the full match ("\nSUMMARY:...") and
the next indexes contain the group
matches.
String.match(regexp) is
supposed to return an array with the
matches. In my browser it doesn't (Safari on Mac returns only the full
match, not the groups), but
Regexp.exec(string) works.
You need to use the m flag:
multiline; treat beginning and end characters (^ and $) as working
over multiple lines (i.e., match the beginning or end of each line
(delimited by \n or \r), not only the very beginning or end of the
whole input string)
Also put the * in the right place:
"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^ ^
//-----------------------------------------------------------------------|
Your regular expression most likely wants to be
/\nSUMMARY:(.*)$/g
A helpful little trick I like to use is to default assign on match with an array.
var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];
This way you don't get annoying type errors when you go to use arr
This code works:
let str = "governance[string_i_want]";
let res = str.match(/[^governance\[](.*)[^\]]/g);
console.log(res);
res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.
By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!
You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp
Good luck.
(.*) instead of (.)* would be a start. The latter will only capture the last character on the line.
Also, no need to escape the :.
You should use this :
var arr = iCalContent.match(/^SUMMARY\:(.)*$/g);
return(arr[0]);
this is how you can parse iCal files with javascript
function calParse(str) {
function parse() {
var obj = {};
while(str.length) {
var p = str.shift().split(":");
var k = p.shift(), p = p.join();
switch(k) {
case "BEGIN":
obj[p] = parse();
break;
case "END":
return obj;
default:
obj[k] = p;
}
}
return obj;
}
str = str.replace(/\n /g, " ").split("\n");
return parse().VCALENDAR;
}
example =
'BEGIN:VCALENDAR\n'+
'VERSION:2.0\n'+
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
'BEGIN:VEVENT\n'+
'DTSTART:19970714T170000Z\n'+
'DTEND:19970715T035959Z\n'+
'SUMMARY:Bastille Day Party\n'+
'END:VEVENT\n'+
'END:VCALENDAR\n'
cal = calParse(example);
alert(cal.VEVENT.SUMMARY);