Re-replacing in regex [duplicate] - javascript

This question already has answers here:
Regex matching 5-digit substrings not enclosed with digits
(2 answers)
Closed 2 years ago.
I am creating a function that replaces the string with a
~(number)~.
Now let's say I have a string that says
This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2
I want to replace all the 2 in a string with ~86~ but when I am doing so the 2 in ~26~ and ~524~ also getting replaced to ~~86~6~ and ```~5~86~4~.
function replaceGameCoordinate() {
var string = `This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2`
var replaceArr = ['2'];
let patt = new RegExp(`${replaceArr[0]}`, 'gm')
var newString = string.replace(patt, "~86~");
console.log(newString);
}
replaceGameCoordinate();
The expected output should be :
This is the replacement of ~26~ and ~524~. We still have ~86~ cadets left. Have~86~go for the next mission.~86~

So you need a different regex rule. You don't want to replace 2. You want to replace 2 when it's not next to another number or ~.
In order to do this, you can use lookaheads and lookbehinds (although lookbehinds are not yet supported by regexes in JS, I believe, but at least with lookaheads) :
const input = "This is the replacement of ~26~ and ~524~. We still have 2 cadets left. Have2go for the next mission.2";
const regex = /2(?![\d~])/gm // Means : "2 when it's not followed by a digit \d or a ~"
console.log( input.replace(regex, "~86~" ) )

Related

Replacing only exact matches in Regex [duplicate]

This question already has answers here:
How can I match a whole word in JavaScript?
(4 answers)
Closed 4 months ago.
I have a javascript function that replaces strings that match against a profanity library with symbols.
eg. damn is transformed into ##$%&!
However, this replace is non-discriminating, and will transform partial matches as well.
eg. classic is transformed into cl##$%&!ic
I'm very new to TS/JS and Regex and would like some help understanding this function's arguments and how to modify them for only exact matches.
this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
To avoid partial matches, the normal solution is to surround what you want to match with word boundaries \b.
The following example assumes that profanities does not contain any words that contain regex special characters.
Notice that the "shit" in "mishit" and the "ass" in "class" do not get replaced.
const profanities = ['damn', 'shit', 'ass'];
// As regex literal: /\b(?:damn|shit|ass)\b/
const re = new RegExp('\\b(?:' + profanities.join('|') + ')\\b', 'gi');
const text = "Damn, another mishit. I am shit at pool. Time to get my ass to class.";
console.log(text.replace(re, '##$%&!'));

javascript remove a exact index character from the string [duplicate]

This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 1 year ago.
let test = 'This is the test string';
console.log(test.substr(3));
console.log(test.slice(3));
console.log(test.substring(3));
Theese methods are removing first 3 character. But i want to remove only third character from the string.
The log has to be: ' Ths is the test string'
İf you help me i will be glad. All examples are giving from the substr, slice eg. eg. Are there any different methods?
First, get the first 3 chars, then add chars 4-end, connect those to get the desired result:
let test = 'This is the test string';
let res = test.substr(0, 2) + test.substr(3);
console.log(res);
Since substr uses the following parameters
substr(start, length)
Start The index of the first character to include in the returned substring.
Length Optional. The number of characters to extract.
If length is omitted, substr() extracts characters to the end of the string.
We can use test.substr(3) to get from the 3'th to the last char without specifying the length of the string
const test = 'This is the test string';
const result = test.slice(0, 2) + test.slice(3);
console.log(result);
You can achieve this by concatenating the two parts of the string, using .slice().
You can achieve it using substring method and concatenating the strings
str = "Delete me ";
function del_one_char(string , removeAt){
return string.substring(0, removeAt) + string.substring( removeAt + 1, string.length);
}
console.log(del_one_char(str , 2))
// result one character at 2nd position is deleted

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

How to find a particular pattern? [duplicate]

This question already has an answer here:
Checking symbols in string in Javascript
(1 answer)
Closed 8 years ago.
Hi I have to find a pattern in Javascript where each letter present must be preceded and followed by + sign.
Is there a way to achieve that using regex?
Suppose if my string is ++3+4++3+ , it is true
whereas if my string is 3+4++3+, it is false
You can use this regex:
/^(\++\d+(?=\+))+\++$/
Code:
var re = /^(\++\d+(?=\+))+\++$/;
var s1 = '++3+4++3+'
var s2 = '3+4++3+'
re.test(s1);
true
re.test(s2);
false
RegEx Demo
((+)+[0-9])+(++)
This says (match one or more of +, match one [0-9]) one or more times, match at least one + at the end of the string
++3+4++3+ == true
3+4++3+ == false
This site saves many hours of regex suffering: http://www.regexr.com/
JS:
var str = "++3+4++3+";
var patt = /((\+)+[0-9])+(\++)/;
var result = patt.test(str);

replace Nth occurence in string - JavaScript [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 9 years ago.
I'm sure this was supposed to work, but I can't get it doing what I want it to:
new_str = old_str.replace(3, "a");
// replace index 3 (4th character) with the letter "a"
So if I had abcdef then above should return abcaef but I must have gotten something wrong. It is changing characters, but not the expected ones.
Either native JS or jQuery solution is fine, whatever is best (I'm using jQuery on that page).
I've tried searching but all tutorials talk of Regex, etc. and not the index replace thing.
You appear to want array-style replacement, so convert the string into an array:
// Split string into an array
var str = "abcdef".split("");
// Replace char at index
str[3] = "a";
// Output new string
console.log( str.join("") );
Here are three other methods-
var old_str= "abcdef",
//1.
new_str1= old_str.substring(0, 3)+'a'+old_str.substring(4),
//2.
new_str2= old_str.replace(/^(.{3}).(.*)$/, '$1a$2'),
//3.
new_str3= old_str.split('');
new_str3.splice(3, 1, 'a');
//return values
new_str1+'\n'+new_str2+'\n'+ new_str3.join('');
abcaef
abcaef
abcaef

Categories

Resources