Replace match last instance of pattern in a string - javascript

I want to only show the value after the - as shown below.
$(function(){
var aa = "ABCDEFGHIJKLMNOPQRS-TUVEXYZ";
var bb = aa.substring(aa.indexOf("-") + 1);
$('#one').text(bb);
});
$(function(){
var cc = "ABC-DEFGHIJ-KLMNOPQRS-TUVEXYZ";
var dd = cc.substring(cc.indexOf("-") + 1);
$('#two').text(dd);
});
this outputs
<div id="one">TUVEXYZ</div>
<div id="two">DEFGHIJ-KLMNOPQRS-TUVEXYZ</div>
The first one works as there is only one dash however when there is multiple dashes my code doesn't work as it just looks for the first -. How would I go about looking for the last - only?
eg If my code was working like I want it to I would expect my end result to look like this.
<div id="one">TUVEXYZ</div>
<div id="two">TUVEXYZ</div>

Use lastIndexOf
var dd = cc.substring(cc.lastIndexOf("-") + 1);

Using regex:
var myregexp = /[^-]*$/;
var result = myregexp.exec(subject)[0];
This regex matches any number of non-dash characters, anchored to the end of the string, which effectively matches everything that follows after the last dash (or the entire string if there is no dash).

This might be the regex you are looking for :)
var.replace( /(?:.*)\-(.*?)$/, $1 ); // or "$1", not really shure in JS

Related

Add in value before single quote (')

I want to add in value before the end of a single quote. Please do help me thanks!
var example = [['2019-02-10', 6.2]],[['2019-03-10', 6.2]]
After replacement
var example = [['2019-02-10 0:00AM' , 6.2]], [['2019-03-10 0:00AM' , 6.2]]
I found this code but unfortunately only for the comma.
var er = rep.replace(/\s*,\s*/g, " 0:00AM , ");
You need some regexp to make it work, please try this
your RegExp should look like this
var regexp = /(\'[a-zA-Z_0-9-]+)\'?/g;
so you should have a string like this:
var st = "[['2019-02-10', 6.2]],[['2019-03-10', 6.2]]";
then you can replace the desired content like this
st.replace(regexp, "$1 0:00AM'")
notice that $1 represent the first match regexp against the string
so finally you should have it like this
"[['2019-02-10 0:00AM', 6.2]],[['2019-03-10 0:00AM', 6.2]]"
I hope it can help you

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

Remove all content after last '\' is not working

I'm trying to rename a document, I want to remove all the content after the last '\' and then give it another name.
I did it like this but it doesn't seem to be working:
var newDocName = documentPath.replace(/\/$/, '');
var newDocName = newDocName + "\test.pdf";
The '\' doesn't get removed after the first line of code.
Any idea what am I doing wrong?
/\/$/ means you want to match a / if it's the last character in the string meaning this code would replace the very last / if, and only if, it's at the end of the string.
If you want to remove the content after the last \ then you can use a combination of split to split the string on \s then use slice to get everything but the last element. Finally, use join to bring them all back together.
var uri = 'path\\to\\my\\file.ext';
var parts = uri.split('\\');
var withoutFile = parts.slice(0, parts.length - 1);
var putItBackTogether = withoutFile.join('\\');
var voila = putItBackTogether + '\\new-file.name';
console.log(voila);
It is forward slash, use \\ istead.
Try to substitute it for:
var newDocName = documentPath.replace(/\\/$/, '');
Your REGEX has a bad format: you should escape your backquotes (\).
So it may be:
var newDocName = documentPath.replace(/[\\/]$/, '');
var newDocName = newDocName + "\\test.pdf";
This regular expression will search for \ or / at the end ($) of you path. You could use regex101 to test your regular expressions.
You also should consider not using regular expressions when you don’t need them:
var newDocName = documentPath[documentPath.length - 1] == "\\" ? documentPath + "test.pdf" : documentPath + "\\test.pdf";

discard dynamic characters in string with replace()

for example 21/10/2013.. I want to remove the /2013..
replace('/2013', '') work but the date might be other value like 2014, 2015 and so on
This removes everything from the last / onwards:
var str = "21/10/2013";
var new_str = str.substring(0,str.lastIndexOf('/'));
Try:
'21/10/2013'.replace(/\/\d+$/,''); // 21/10
which removes the last "/" and any digits following to the end of the string.

how to extract string part and ignore number in jquery?

I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");

Categories

Resources