Need to replace a character in a string with two new values - javascript

var Str = "_Hello_";
var newStr = Str.replaceAll("_", "<em>");
console.log(newStr);
it out puts <em>Hello<em>
I would like it to output <em>Hello</em>
but I have no idea how to get the </em> on the outer "_", if anyone could help I would really appreciate it. New to coding and finding this particularly difficult.

Replace two underscores in one go, using a regular expression for the first argument passed to replaceAll:
var Str = "_Hello_";
var newStr = Str.replaceAll(/_([^_]+)_/g, "<em>$1</em>");
console.log(newStr);
NB: it is more common practice to reserve PascalCase for class/constructor names, and use camelCase for other variables. So better str =, ...etc.

I would phrase this as a regex replacement using a capture group:
var str = "_Hello_ World!";
var newStr = str.replace(/_(.*?)_/g, "<em>$1</em>");
console.log(newStr);

Related

replace – with - using replace()

I have been using
var str = "Artist - Song";
str = str.replace("-", "feat");
to change some texts to "-".
Recently, I've noticed another "–" that the above code fails to replace.
This "–" seems a bit longer than the normal "-".
Is there any way to replace the longer one with the shorter "-"?
Any help is appreciated. Thanks
EDIT.
This is how the rest of the code is written.
var befComma = str.substr(0, str.indexOf('-'));
befComma.trim();
var afterhyp = str.substr(str.indexOf("-") + 1);
var changefeat = befComma.toUpperCase();
This "–" seems a bit longer than the normal "-".
Is there any way to replace the longer one with the shorter "-"?
Sure, you just do the same thing:
str = str.replace("–", "-");
Note that in both cases, you'll only replace the first match. If you want to replace all matches, see this question's answers, which point you at regular expressions with the g flag:
str = str.replace(/-/g, "feat");
str = str.replace(/–/g, "-");
I'm not quite sure why you'd want to replace the longer one with the shorter one, though; don't you want to replace both with feat?
If so, this replaces the first:
str = str.replace(/[-–]/, "feat");
And this replaces all:
str = str.replace(/[-–]/g, "feat");
Give this a shot:
var str = "Artist – Song";
str = str.replace("–", "-"); // Add in this function
str = str.replace("-", "feat");
This should replace the slightly longer "–" with the shorter more standard "-".

Regular Expression to replace part of a string

I need to replace part of a string, it's dynamically generated so I'm never going to know what the string is.
Here's an example "session12_2" I need to replace the 2 at the end with a variable. The "session" text will always be the same but the number will change.
I've tried a standard replace but that didn't work (I didn't think it would).
Here's what I tried:
col1 = col1.replace('_'+oldnumber+'"', '_'+rowparts[2]+'"');
Edit: I'm looking for a reg ex that will replace '_'+oldnumber when it's found as part of a string.
If you will always have the "_" (underscore) as a divider you can do this:
str = str.split("_")[0]+"_"+rowparts[x];
This way you split the string using the underscore and then complete it with what you like, no regex needed.
var re = /session(\d+)_(\d+)/;
var str = 'session12_2';
var subst = 'session$1_'+rowparts[2];
var result = str.replace(re, subst);
Test: https://regex101.com/r/sH8gK8/1

JavaScript - strip everything before and including a character

I am relatively new to RegEx and am trying to achieve something which I think may be quite simple for someone more experienced than I.
I would like to construct a snippet in JavaScript which will take an input and strip anything before and including a specific character - in this case, an underscore.
Thus 0_test, 1_anotherTest, 2_someOtherTest would become test, anotherTest and someOtherTest, respectively.
Thanks in advance!
You can use the following regex (which can only be great if your special character is not known, see Alex's solution for just _):
^[^_]*_
Explanation:
^ - Beginning of a string
[^_]* - Any number of characters other than _
_ - Underscore
And replace with empty string.
var re = /^[^_]*_/;
var str = '1_anotherTest';
var subst = '';
document.getElementById("res").innerHTML = result = str.replace(re, subst);
<div id="res"/>
If you have to match before a digit, and you do not know which digit it can be, then the regex way is better (with the /^[^0-9]*[0-9]/ or /^\D*\d/ regex).
Simply read from its position to the end:
var str = "2_someOtherTest";
var res = str.substr(str.indexOf('_') + 1);

JavaScript String.replace() all instances and escaping

I have a string: Dkjd(Dk39dD_2=3499(39482&#6293jd
I would like to escape all characters of my choosing (say, _#-) with a backslash. I'm confused how I would do this with String.replace. Can I use the original value in the new value var? Can I use RegEx to do this? Thanks.
No need to use function, use backreference:
source.replace(/([_#\-])/g, "\\$1")
The thing in parentheses can be referenced as $1 in replacement string.
This should be easy with a regex.
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/[_#-]/g, function(match){
return '\\'+match;
});
console.log(str); // Dkjd(Dk39dD\_2=3499(39482&\#6293jd
Simply,
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/([_#-])/g, '\\$1');
Hope it helps.

Javascript search and replace sequence of characters that contain square brackets

I'm trying to search for '[EN]' in the string 'Nationality [EN] [ESP]', I want to remove this from the string so I'm using a replace method, code examaple below
var str = 'Nationality [EN] [ESP]';
var find = "[EN]";
var regex = new RegExp(find, "g");
alert(str.replace(regex, ''));
Since [EN] is identified as a character set this will output the string 'Nationality [] [ESP]' but I want to remove the square brackets aswell. I thought that I could escape them using \ but it didn't work
Any advice would be much appreciated
Try setting your regex this way:
var regex = /\[EN\]/g;
If you just want to replace a single instance of it you can just str = str.replace("[EN] ", ""); otherwise; var find = "\\[EN\\]";.

Categories