I want to replace the underscore that precedes a date in a string e.g.
thequick_brown_20210813_fox
To:
thequick_brown_red_20210813_fox
I.e. replace that underscore with _red_
This captures the date part: (20\d{2})(\d{2})(\d{2})
And to replace I assume I can just use str.replace
But not sure how I can capture the underscore that precedes it.
You can try the following RegEx with Positive Lookahead:
/_(?=\d{8})/
Where:
_ matches the character _
(?=\d{8}) - Positive Lookahead
\d - matches a digit (equivalent to [0-9])
{8} - matches the previous token exactly 8 times
var str = 'thequick_brown_20210813_fox';
var patt = /_(?=\d{8})/;
str = str.replace(patt, '_red_');
console.log(str);
This works
And as bonus I have a super robust regex for dates
const str = 'thequick_brown_20210813_fox';
const re = /_(?=\d{4}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))/;
const newStr = str.replace(re, '_red_');
console.log(newStr);
The regex is from here
This is what I came up with using the RegEx you provided.
let str = "thequick_brown_20210813_fox";
let newStr = "";
let regex = /(20\d{2})(\d{2})(\d{2})/;
let splits = str.split(regex);
newStr += splits[0] + "red_";
for(let i=1; i<splits.length; i++){
newStr += splits[i];
}
console.log(newStr);
I would use as a matching regex:
_(?=20[0-9]{6})
_ Matches underscore if ...
(?=20[0-9]{6}) This is a lookahead assertion that the following characters must be '20' followed by 6 digits.
Note that the above only matches the underscore when followed by '20' followed by an additional 6 digits. So we simply replace the underscore with '_red_':
let s = 'thequick_brown_20210813_fox';
s = s.replace(/_(?=20[0-9]{6})/g, '_red_');
console.log(s);
Related
var str = "lala";
var newStr = str.replace('l', 'm');
The value of newStr becomes 'mala', as the replace method finds the first occurrence of character in the string and replaces the character and then stops.
But I want the output "lama".
How can I achieve it?
You can use regex for this:
var str = "lala";
var newStr = str.replace(/l([^l]*)$/, 'm$1'); // lama
console.log(newStr);
This pattern matches an l followed by any number of characters that are not l until the end of the string. This will only match one time since the string ends only once (i.e in "lalblc" it matches "lc"). Then it replaces "lc" with "m" followed by the group of letters after the l (which is "c"). In the end, you are left with the original string but with the last l replaced with m.
[^l] means "any letter that is not l"
* means "any number of times (0 or more)"
The parenthesis create a capturing group which can be referenced using $1 in the replacement.
If you will be doing this frequently, it would be useful to move this to a function. You can make a function, replaceLast that can be called on strings by doing:
String.prototype.replaceLast = function (search, replace) {
return this.replace(new RegExp(search+"([^"+search+"]*)$"), replace+"$1");
}
str = "lala";
newStr = str.replaceLast("l", "m");
console.log(newStr);
You can match everything up to an "l" followed by anything that's not an "l":
var str = "lala";
var newStr = str.replace(/(.*)l([^l]*)$/, "$1m$2");
console.log(newStr);
The first group, (.*), will consume as much of the string as it can. The second group, ([^l]*)$, will match the rest of the source string after the last "l".
Here i've created a custom function also i've avoided using any regex since it's quite difficult for any beginner to understand.
var str = "lala";
const customReplace = (replaceChar, replaceWith, str) => {
const lastIndex = str.lastIndexOf(replaceChar);
const leftPortion = str.slice(lastIndex);
const rightPortion = str.slice(lastIndex+1);
return `${leftPortion}${replaceWith}${rightPortion}`;
}
console.log(customReplace('l', 'm', str))
You can use reverse, replace and reverse again.
You could take a search for l which is not followed by optional non l characters and an l.
var str = "lala",
newStr = str.replace(/l(?![^l]*l)/, 'm');
console.log(newStr);
or you can use Look ahead in RegEx to find the last character :
var str = "lala";
var newStr = str.replace(/l(?!.*l)/, 'm');
console.log(newStr);
for more information you can read this link
Here is a straightforward way to replace, a bit silly but it works as well
var str = "lalalc";
var newStr = [...str];
newStr[str.lastIndexOf('l')] ='m';
newStr.join('');
You can use this Regex to replace second occurance of letter:
var str = "lala";
var newStr = str.replace(/(?<=l.*?)l/,"m");
console.log(newStr);
match a path for a specific word and a / and any characters that follow.
For example.
const str = 'cars/ford';
const isCars = str.match('cars');
What I want to do is make sure it matches cars and has a slash and characters after the / then return true or false.
The characters after cars/... will change so I can't match it excatly. Just need to match any characters along with the /
Would love to use regex not sure what it should be. Looking into how to achieve that via regex tutorials.
var str = "cars/ford";
var patt = new RegExp("^cars/"); //or var patt = /^cars\//
var res = patt.test(str); //true
console.log(res);
https://www.w3schools.com/js/js_regexp.asp
https://www.rexegg.com/regex-quickstart.html
You could use test() that returns true or false.
const str = "cars/ford";
const str2 = "cars/";
var isCars = (str)=>/^cars\/./i.test(str)
console.log(isCars(str));
console.log(isCars(str2));
Here is a quick regex to match "cars/" followed by any characters a-z.
(cars\/[a-z]+)
This will only match lowercase letters, so you can add the i flag to make it case insensitive.
/(cars\/[a-z]+)/i
It is a basic regular expression
var str = "cars/ford"
var result = str.match(/^cars\/(.*)$/)
console.log(result)
^ - start
cars - match exact characters
\/ - match /, the \ escapes it
(.*) - capture group, match anything
$ - end of line
Visualize it: RegExper
How to Replace -84 in a string: my-name-is-dude-84 with '' Regex?
I means the last '-' + number
I tried :
string = 'my-name-is-dude-84';
let regex = /[^\-*][1-9]/;
let specialChar = string.replace(regex, '');
then I received is my-name-is-dude-
I expect my string will be: my-name-is-dude
You're close, but this is what you need to do (I guess)
string = 'my-name-is-dude-84';
let regex = /-\d+$/;
let specialChar = string.replace(regex, '');
document.write(specialChar);
Your [^\-*] tries to match all characters but \, - and *. Also [1-9] only matches one digit (between 1 and 9). Use \d (all digits), and add a + to make it match one or more. Also, adding an end of string anchor $ to it makes it only match the hyphen+number at the end of the string.
You can use this regex (.*?)-\d+$
regex demo
JavaScript demo
string = 'my-name-is-99-dude-84';
let regex = /(.*?)-\d+$/;
let specialChar = string.replace(regex, "$1");
document.write(specialChar);
I have a string: '100 - 250'
I want to append the pound symbol to start of each number so it becomes:
£100 - £250
What's the best way to do this using Javascript?
I tried using regex /[0-9]/ to identify the numbers, I would have then just appended the pound symbol and recreated my string. But this regex identifies the individual numbers so when executing this regex on '100 - 250', I am getting back [1, 0...].
Here is a way to go:
var str = "100 - 250";
str = str.replace(/(?=\b\d+\b)/g, '£');
console.log(str);
Try this.
var regex = /(\d+)(\s*\-\s*)(\d+)/,
myString = '100 - 250';
myString.replace(regex, "£$1$2£$3");
var str = "100 - 250";
var arr = str.match(/\d+/g);
arr.forEach(function(item, index, ar){ar[index] = "$"+item;});
console.log("output - "+arr.join(" - "));
Nice one-liner
str.match(/\d+/g).map(function(num) { return "£"+num; }).join(" - ");
Your solution almost complete in case you need to only deal with integer values.
In order to add a pound sign in front of each digit at the number start use
str = str.replace(/\b[0-9]/g, '£$&');
^^ ^^
That is, you needed a word boundary (\b) and a backreference to the whole match ($&) in your replacement pattern.
Note that /g modifier will make multiple replacements if there is more than 1 match in the string.
var str = "100 - 200";
str = str.replace(/\b[0-9]/g, '£$&');
console.log(str);
A bonus solution for integers and floats:
var str = "100 - 200 - 550.55";
str = str.replace(/(^|[^.])\b([0-9])/g, '$1£$2');
// or
// str = str.replace(/\d*\.?\d+/g, '£$&');
console.log(str);
The best way to explain this is by example. I'm using jQuery to do this.
Example I have a string
var str = "1.) Ben"
how can I dynamically omit the character 1.) including the space such that str === "Ben"
str can be dynamic such that order can increment from ones, tens, to hundreds.
E.G.
var str = "52.) Ken Bush"
or
var str = "182.) Hailey Quen"
Expected output
str === "Ken Bush"
or
str === "Hailey Quen"
Example
var str = "182.) Hailey Quen"
var test = str.split(') ');
test = test[1];
//output "Hailey Quen"
You can use regex replacement to get what you want.
var str = "182.) Hailey"
var newStr = str.replace(/^\d+\.\)\s*/, '')
// Hailey
var s = "1456.) Hard Spocker".replace(/^\d+\.\)\s*/, '')
// Hard Spocker
^ makes sure that the pattern is matched at the start of the string only
\d+ will match one or more digits.
\. will match the . with escaping
) is a symbol so we need to escape it using \ as \)
\s* will match one or more spaces.
You can learn about these symbols here.
Try using .substring() and .indexOf() as shown :-
var str = "182.) Hailey Quen"
alert(str.substring(str.indexOf(' ')))
DEMO
OR use .split() as shown :-
var str = "182.) Hailey Quen"
alert($.trim(str.split(')')[1]))
DEMO
You can do it regular expression,
var str = "52.) Ken".replace(/\d+\.\)\s/g,"");
console.log(str); //Ken
DEMO
If you have zero or more than zero spaces after the ) symbol then you can use *,
var str = "52.) Ken".replace(/\d+\.\)\s*/g,"");
console.log(str); //Ken
Dismantling regex used,
/ states regex left border
\d d states normal character d, if we want to make it match
numbers then we have to escape it with \
+ It states that one or more number should be there.
\. Again . is a metacharacter to match any valid character, so
escape it.
\) Parenthesis is also a metacharacter to close a group, escape
it.
\s* 12.) can be followed by zero or more spaces.
/ states regex right boundary.
g global flag, which used to do a search recursively.
You can do it like this
var testURL = "182.) Hailey Quen";
var output = testURL.substring(testURL.lastIndexOf(")") + 1).trim();
console.log(output);
*trim function will help to remove extra space if any.Hope it will help