How to replace the just end of a string - javascript

I want a regex that replaces the end of a string if it ends in '.id'. E.g if I have a string called 'password' nothing gets replaced. If I have another string called 'idiot', nothing gets replaced. But, if I have 'email.id' it gets replaced with an empty string.
I made using of loadash's trimEnd but I noticed it was trimming the letter d in password and the result was passwor.

Search with \.id$ and replace with ''. Regex101 Demo

simply do with pattern /\.id$/g using regex
Explanation:
\.id is match the .id in the string
$ is match the position at end of the string
Demo Regex
console.log('password'.replace(/\.id$/g,""))
console.log('email.id'.replace(/\.id$/g,""))

If the ".id" is static you can use
var newstr = str.split('.id').join('');
If it is dynamic you can use
var newstr = str.substr(0, str.indexOf('.'));

Related

How to get next 3 characters after a substring if it exist inside a string?

I have this string that's. The &# substring is common but number after it changes in almost every object of my JSON data. So I want to detect if there is this substring, then get next three characters after it replace it with something else. How can I do it?
You can do it like this
var para = 'that's';
para = para.substr(para.indexOf('#')+1, 3);
syntax:
substr(start, length)
indexOf(searchvalue, [start])
Assuming you want to replace everything from &# until ; (if not, please update your question by specifying expected output):
You can use String.prototype.replace() with a regular expression:
var para = 'some string ' middle † end';
para = para.replace(/&#([\d]*);/g, 'replacement');
The g modifier is important to replace all occurences in the string.
With the RegEx used, you can include the found number (between &# and ;) in the replacement string by using $1.
you can define and use a utility function to replace HTML entities like that:
function decode(text, replaceWith = '') {
return text.replace(/&#(\d+);/g, replaceWith)
}

Javascript Regex match everything after last occurrence of string

I am trying to match everything after (but not including!) the last occurrence of a string in JavaScript.
The search, for example, is:
[quote="user1"]this is the first quote[/quote]\n[quote="user2"]this is the 2nd quote and some url https://www.google.com/[/quote]\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.
Edit: I'm looking to match everything after the last quote block. So I was trying to match everything after the last occurrence of "quote]" ? Idk if this is the best solution but its what i've been trying.
I'll be honest, i suck at this Regex stuff.. here is what i've been trying with the results..
regex = /(quote\].+)(.*)/ig; // Returns null
regex = /.+((quote\]).+)$/ig // Returns null
regex = /( .* (quote\]) .*)$/ig // Returns null
I have made a JSfiddle for anyone to have a play with here:
https://jsfiddle.net/au4bpk0e/
One option would be to match everything up until the last [/quote], and then get anything following it. (example)
/.*\[\/quote\](.*)$/i
This works since .* is inherently greedy, and it will match every up until the last \[\/quote\].
Based on the string you provided, this would be the first capturing group match:
\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.
But since your string contains new lines, and . doesn't match newlines, you could use [\s\S] in place of . in order to match anything.
Updated Example
/[\s\S]*\[\/quote\]([\s\S]*)$/i
You could also avoid regex and use the .lastIndexOf() method along with .slice():
Updated Example
var match = '[\/quote]';
var textAfterLastQuote = str.slice(str.lastIndexOf(match) + match.length);
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;
Alternatively, you could also use .split() and then get the last value in the array:
Updated Example
var textAfterLastQuote = str.split('[\/quote]').pop();
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

String operation in javascript

How can I get only 'ABCD' from string 'ABCD150117T15' in java script.
I would like strip rest of the string from 'ABCD' in this example and generally everything until but excluding the first number character.
thanks
You can match for a-z
'ABCD150117T15'.match(/^[a-z]+/i)
you can match anything that is not a number
'ABCD150117T15'.match(/^[^\d]+/)
Use regex then to match the first digit, and then subtring it to the text;
var str = 'ABCD150117T15';
var index = str.search(/\d/);
var text = str.substr(0,index);
'ABCD150117T15'.match(/^\D+/)[0]
This would give you everything until the first number then :)

javascript replace text at second occurence of "/"

I have this string
"/mp3/mysong.mp3"
I need to do make this string look like this with javascript.
"/mp3/myusername/mysong.mp3"
My guess would be to find second occurrence of "/", then append "myusername/" there or prepend "/myusername" but I'm not sure how to do this in javascript.
Just capture the characters upto the second / symbol and store it into a group. Then replace the matched characters with the characters inside group 1 plus the string /myusername
Regex:
^(\/[^\/]*)
Replacement string:
$1/myusername
DEMO
> var r = "/mp3/mysong.mp3"
undefined
> r.replace(/^(\/[^\/]*)/, "$1/myusername")
'/mp3/myusername/mysong.mp3'
OR
Use a lookahead.
> r.replace(/(?=\/[^/]*$)/, "/myusername")
'/mp3/myusername/mysong.mp3'
This (?=\/[^/]*$) matches a boundary which was just before to the last / symbol. Replacing the matched boundary with /myusername will give you the desired result.
This works -
> "/mp3/mysong.mp3".replace(/(.*?\/)(\w+\.\w+)/, "$1myusername\/$2")
"/mp3/myusername/mysong.mp3"
Demo and explanation of the regex here
use this :
var str = "/mp3/mysong.mp3";
var res = str.replace(/(.*?\/){2}/g, "$1myusername/");
console.log(res);
this will insert the text myusername after the 2nd / .

Trimming String in Javascript

I have string like var a=""abcd""efgh"".How do I print the output as abcd""efgh by removing first and last double quote of a string I used a.replace(/["]/g,'') but it is removing all the double quotes of a string.How do i get the output as abcd""efgh.Suggest me an idea.
You can use
var a='"abcd""efgh"';
a.replace(/^"+|"+$/g, '');
From the comments here is the explanation
Explanation
There are 2 parts ^"+ and "+$ separated by | which is the regex equivalent of the or
^ is for starts-with and "+ is for one or more "
Similarly $ is for ends-with
The //g is for global replacement otherwise the only the first occurrence will be replaced
Try use this
var a='"abcd""efgh"';
a.replace(/^"|"$/g, '');

Categories

Resources