Regex or lastIndexOf when removing last instance of a string - javascript

I couldn't apply answers to other similar questions (trying to replace the last occurrence of a string) because I am having trouble with the syntax.
I'm trying to replace the last occurrence of a string. The value of the string is stored in a variable that is passed to the .replace() method like this:
var str += some additive strings;
var del = a string that lives within str; // the value is dynamic
str = str.replace(del$, ''); // this doesn't work to remove the last occurrence of `del` in str
As I understand it the $ argument looks for the last occurrence of a string within a regex; but I can't figure out how to use it alongside a variable passed to .replace(). Any suggestions?

If you want to use the RegExp with a $, do it like this:
var str += 'some additive strings';
var re = new RegExp('a string that lives within str$');
str = str.replace(re, '');

str = str.substring(0, str.length - del.length);

You can use lastIndexOf() with slice()
Example:
var str ="HI this is cool isn't it? cool";
var del='cool';// put whatever here
var index = test.lastIndexOf(del);
var length=del.length;
if(index!=-1)
var removeStr=test.substr(index,length);
str.replace(removeStr,''); // HI this is cool isn't it?
Mate, this is just an answer. You'll need to use it according to your needs.
Updated Live demo:http://jsfiddle.net/n2Kgn/2

Related

add an element "/" in particular position in string with Javascript

I want to add an element "/" within a string, but only a specific position of it, e.g. from string "20180101" to expect result like "2018/01/01".is anyone know what syntax or how to make it happen.I'm still beginner in javascript
any help would be really appreciate.
Here is one option using replace with a regex pattern:
var input = "20180419";
console.log(input.replace( new RegExp("^(\\d{4})(\\d{2})(\\d{2})", "gm"),"$1/$2/$3"));
Use substr approach to get the result:
var str = "20180101";
str = str.substr(0, str.length-4) + '/' + str.substr(4, str.length);
str = str.substr(0, str.length-2) + '/' + str.substr(7, str.length);;
console.log(str);
Another option creating an array of sub-strings with slice (note that this would work the same way with substring here), and then joining each part with a /:
let s = "20180101"
let result = [s.substring(0,4), s.substring(4,6), s.substring(6,8)].join('/')
In such cases, you may find useful to treat your string as an array of digits.
Get an array of digits from your string:
let myString = '20180101';
let myArray = myString.split('') //the '' splitter means it will just split anything
Then, add into your array of digits, the desired '/' digit in the desired positions. Refer to the splice method for more information.
myArray.splice(4,0,'/');
myArray.splice(7,0,'/');
Then, build your string:
myString = myArray.join(''); //the opposite of splitting
console.log(myString) // outputs '2018/01/01'

Substring a part of a string using angularjs

I have a string like this string(1), I want to get substring remove the last part to obtain just string any suggestions please!!
PS.the string could be: sringggg(125).
You can use various options to get the desired string.
//With regular expression with split() and fetch the first element of array
console.log('sringggg(125)'.split(/\(\d+\)/)[0]);
//Using string with split() and fetch the first element of array
console.log('sringggg(125)'.split('(')[0]);
//Using substr and indexOf
var str = 'sringggg(125)'
console.log(str.substr(0, str.indexOf('(')));
References
String.prototype.split()
String.prototype.indexOf()
If string is always in same pattern and ' ( ' is a separator use split .
var string = 'string(1)'
var result = string .split('(')[0];
Try using regexp
var tesst = "string(1)"
var test = tesst.match(/^[^\(]+/);
// test = "string"

Javascript Replace with Regex Match Not Working

I'm trying to truncate some longitude coordinates without any rounding issues. I thought replace() would be the simplest way to do this.
My regex is correct, but I'm apparently not using replace correctly.
Here's my stripped down example. I need to strip all decimal points after the 8th position
var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));
What's happening is replace() is stripping the match and leaving me with the remainder prepended with "$1". The result is:
$1999997
You've got some answers of RegExp. Alternatively, you could just find the index of the point and retrieve a substring, if you don't care about rounding.
var str = '-81.82297519999997';
var truncated = str.substring(0, str.indexOf('.') + 9); // this will give you 8 fractions
console.log(truncated); // "-81.82297519"
You must add matching groups in parentheses to match something that you can refer to with $1 while replacing. For example:
var truncRegex = /(-?\d+?\.\d{8})\d*/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));
replace() function replaces everything it matches based on regular expression. Your code simply replaces -DD.DDDDDDDD with '$1' string.
You can still use expression you provided, but you will have to use match, not replace, e.g.:
var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.match(truncRegex)[0]);
var s = '81.82297519999997';
// Returns "-81.82297519"
s.replace(/(-?\d+\.\d{8})\d*/, '$1');
(-?\d+?\.\d{8})|.*
Try this.Replace by $1.See demo.
https://regex101.com/r/eZ0yP4/17
var re = /(-?\d+?\.\d{8})|.*/mg;
var str = '-81.82297519999997';
var subst = '$1';
var result = str.replace(re, subst);

Return only text after last underscore in JavaScript string

If I have a string like so:
var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';
How can I get just the last part of the string after the last underscore?
And in the case there are no underscores just return the original string.
In this case I want just 'hunti'
var index = str.lastIndexOf("_");
var result = str.substr(index+1);
It's very simple. Split the string by the underscore, and take the last element.
var last = str.split("_").pop();
This will even work when the string does not contain any underscores (it returns the original string, as desired).
You can use a regular expression:
'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti'.match(/[^_]*$/)[0];

myString.replace( VARIABLE, "") ...... but globally

How can I use a variable to remove all instances of a substring from a string?
(to remove, I'm thinking the best way is to replace, with nothing, globally... right?)
if I have these 2 strings,
myString = "This sentence is an example sentence."
oldWord = " sentence"
then something like this
myString.replace(oldWord, "");
only replaces the first instance of the variable in the string.
but if I add the global g like this myString.replace(/oldWord/g, ""); it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?
Well, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.
var oldWordRegEx = new RegExp(oldWord,'g');
myString.replace(oldWordRegEx,"");
No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:
myString.split(oldWord).join('')
In the OP's example:
var myString = "This sentence is an example sentence.";
var oldWord = " sentence";
console.log(myString.split(oldWord).join(''));
According to the docs at MDN, you can do this:
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr); // oranges are round, and oranges are juicy.
where /gi tells it to do a global replace, ignoring case.

Categories

Resources