How to add character after a regex match is found - javascript

I want to add a closing bracket to the math expression within the string
var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better.";
var patt1 = /\((d+)/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
The match patter displays (345 and (79. Without changing the content, how can I add a closing bracket so the string look like;
var str = " solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better.

Use negative lookahead assertion.
var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better.";
console.log(str.replace(/(\(\d+)\b(?!\))/g, "$1)"))
(\(\d+) capture \( and one or more digits
(?!\)) only if the match wasn't followed by closing brace )

Check if the an opening brace if followed by numbers, but not by its closing brace after numbers
var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better.";
var output = str.replace( /\([\d]+(?!=\))/g, r => r + ")");
Output
solve this now Math.sqrt(345)+6 is good but Math.sin(79) is better.
Demo
var str = "solve this now Math.sqrt(345+6 is good but Math.sin(79 is better.";
var output = str.replace(/\([\d]+(?!=\))/g, r => r + ")");
console.log(output);
You can include . to allow decimals as well
var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232.";
var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")");
Output
solve this now Math.sqrt(345.5)+6 is good but Math.sin(79.33) is better (232).
Demo
var str = "solve this now Math.sqrt(345.5+6 is good but Math.sin(79.33 is better (232.";
var output = str.replace( /\(\d+(\.(\d)+)?(?!=\))/g, r => r + ")");
console.log(output);

Related

How to capture variable string in replace()?

Code like this:
var v = 'd';
var re = new RegExp('a(.*?)' + v, 'gi');
"abcd".replace(re,re.$1);
I want to get "bc".
Use simply $1 in a string to get the result of the first capturing group:
var re = /a(.*)d/gi
var output = "abcd".replace(re,"$1")
console.log(output) //"bc"
You can do this easily with:
let str = "abcd";
let bc = str.replace(/a(.*)d/g,"$1");
console.log(bc) //bc
The "$1" captures whatever is in the regex () bracket.

how do i split this string into two starting from a specific position

I have this string:
var str=' "123","bankole","wale","","","","xxx" ';
I need to split this string into two. The split should start from the last comma. Resulting in:
' "123", "bankole","wale","","","" ' and ' "xxx" '
I used the below to get the "xxx":
str.split(/[,]+/).pop(); \\""
however note that the last "" can also be "something"
There are many ways to achive this.
You could split your string on commas with split(), then get the last element of the created array with slice(). Then join() the elements left in the first part back into a string.
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -1).join(',')
var end = arr[arr.length-1];
console.log(start);
console.log(end);
In the above code, the part that extracts the last part after the last comma is arr.slice(0, -1). -1 means start looking from the end of the array and go back 1.
So if you need to split from the second last, use arr.slice(0, -2)
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -2).join(',')
var end = arr.slice(-2).join(',')
console.log(start);
console.log(end);
You can simply use String.prototpye.lastIndexOf() and String.prototpye.substring()
var str='"123","bankole","wale","","","","something"';
var lastCommaIndex = str.lastIndexOf(',');
var part1 = str.substring(0, lastCommaIndex);
var part2 = str.substring(lastCommaIndex + 1, str.length);
console.log(part1)
console.log(part2)
It sounds like your regex is already what you're looking for, and that you're simply looking to extract the final segment. This can be done with array_name[array_name.length - 1], as can be seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
console.log(parts[parts.length - 1]);
If you also want to remove the quotes, you can run .replace(/['"]+/g, '') on the extracted string, as is seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
var extracted = parts[parts.length - 1];
console.log(extracted.replace(/['"]+/g, ''));
Hope this helps! :)
If you want to use regex you can use negative lookahead as follows.
var str = ' "123","bankole","wale","","","","something" ';
var splitResult = str.split(/,(?!.*,)/);
console.log(splitResult[0])
console.log(splitResult[1])

Match numbers in a String only once

I´ve got this code, but now I´m trying to match numbers only once.
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /9\d{7}/g;
var result = text.match(regex);
var pos0 = result[0];
var pos1 = result[1];
var pos2 = result[2];
return(pos0 + " " + pos1 + " " + pos2);
Result is: 91308543 91308543 91503362
Result I want: 91308543 91503362
It is possible to add something to my regex so it doesn´t show duplicate values?
I prefer not to use Arrays because in that case I need to use Native Arrays...
I also have a second question, it is possible to create the variables "pos0", "pos1"... automatically?
Thank you!
The regex you are looking for is
(9\d{7})\b(?!.*\1\b)
It uses negative lookahead. See demo.
The second point is achievable through eval:
var result = text.match(regex);
for (var i = 0; i < result.length; i++){
eval('var pos' + i + ' = "' + result[i] + '"');
}
but this does not help you with the return statement.
You should just use:
return(result.join(" "));
You can filter out the duplicates after matching, and use a destructuring assingment to assign to individual variables:
let text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
let regex = /9\d{7}/g;
let [pos0, pos1, pos2] = text.match(regex).filter((v, i, a) => a.indexOf(v) === i);
console.log(pos0);
console.log(pos1);
console.log(pos2);
Try this pattern (9\d{7})(?!.*\1) negative lookahead .Its not allow the duplicate
Demo regex
For more reference
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /(9\d{7})(?!.*\1)/g;
var result = text.match(regex);
console.log(result)

Javascript - remove a string in the middle of a string

Thank you everyone for your great help !
Sorry, I have to edit my question.
What if the "-6.7.8" is a random string that starts with "-" and has two "." between random numbers? such as "-609.7892.805667"?
===============
I am new to JavaScript, could someone help me for the following question?
I have a string AB.CD.1.23.3-609.7.8.EF.HI
I would like to break it into two strings: AB.CD.1.2.3.EF.HI (remove -609.7.8 in the middle) and AB.CD.6.7.8.EF.HI (remove 1.23.3- in the middle).
Is there an easy way to do it?
Thank you very much!
var s = "AB.CD.1.23.3-609.7.8.EF.HI";
var a = s.replace("-609.7.8","");
var b = s.replace("1.23.3-","");
console.log(a); //AB.CD.1.23.3.EF.HI
console.log(b); //AB.CD.609.7.8.EF.HI
You could use
str.replace();
var str = "AB.CD.1.2.3-6.7.8.EF.HI";
var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI"
var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI"
Use split() in String.prototype.split
var myString = "AB.CD.1.23.3-609.7.8.EF.HI";
var splits1 = myString.split("-609.7.8");
console.log(splits1);
var splits2 = myString.split("1.23.3-");
console.log(splits2);
With regular expressions:
s = 'AB.CD.1.23.3-609.7.8.EF.HI'
var re = /([A-Z]+\.[A-Z]+)\.([0-9]+\.[0-9]+.[0-9]+)-([0-9]+\.[0-9]+.[0-9]+)\.([A-Z]+\.[A-Z]+)/
matches = re.exec(s)
a = matches[1] + '.' + matches[2] + '.' + matches[4] // "AB.CD.1.23.3.EF.HI"
b = matches[1] + '.' + matches[3] + '.' + matches[4] // "AB.CD.609.7.8.EF.HI"

Replace last occurrence of character in string

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c';
console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
This will replace it with the contents of the variable replacement:
var str = 'a_b_c',
replacement = '!';
console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"
// Replace last char in a string
console.log(
str1.substring(0,str1.length-2)+"?"
)
// alternative syntax
console.log(
str1.slice(0,-1)+"?"
)
// Replace last underscore in a string
var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax
console.log(
str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)
What about this?
function replaceLast(x, y, z){
var a = x.split("");
a[x.lastIndexOf(y)] = z;
return a.join("");
}
replaceLast("Hello world!", "l", "x"); // Hello worxd!
Another super clear way of doing this could be as follows:
let modifiedString = originalString
.split('').reverse().join('')
.replace('_', '')
.split('').reverse().join('')
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
var someString = "(/n{})+++(/n{})---(/n{})$$$";
var toRemove = "(/n{})"; // should find & remove last occurrence
function removeLast(s, r){
s = s.split(r)
return s.slice(0,-1).join(r) + s.pop()
}
console.log(
removeLast(someString, toRemove)
)
Breakdown:
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
Reverse the string, replace the char, reverse the string.
Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?
// Define variables
let haystack = 'I do not want to replace this, but this'
let needle = 'this'
let replacement = 'hey it works :)'
// Reverse it
haystack = Array.from(haystack).reverse().join('')
needle = Array.from(needle).reverse().join('')
replacement = Array.from(replacement).reverse().join('')
// Make the replacement
haystack = haystack.replace(needle, replacement)
// Reverse it back
let results = Array.from(haystack).reverse().join('')
console.log(results)
// 'I do not want to replace this, but hey it works :)'
This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array)
Anyway, I just thought I'd put it out there in case someone prefers it.
var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'
The '_' can be swapped out with the char you want to replace
And the '-' can be replaced with the char or string you want to replace it with
You can use this code
var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);
alert(str);
This is a recursive way that removes multiple occurrences of "endchar":
function TrimEnd(str, endchar) {
while (str.endsWith(endchar) && str !== "" && endchar !== "") {
str = str.slice(0, -1);
}
return str;
}
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)

Categories

Resources