How to capture variable string in replace()? - javascript

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.

Related

How to get the delimiters that split my string in Javascript?

Let's say I have a string like the following:
var str = "hello=world&universe";
And my regex replace statement goes like this:
str.replace(/([&=])/g, ' ');
How do I get the delimiters that split my string from the above regex replace statement?
I would like the result to be something like this:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];
You could split with a group and then separate the parts.
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);
Here's one way using String.matchAll
const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
But just FYI. The string you posted looks like a URL search string. You probably want to use URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

javascript match returning word boundry

RegEx is not my strong suit. I hope one of you can help me.
I am trying to use javacript.match() to search for all hashed(# at the beginning) words.
and I get a returned white space.
string = "#foo #bar"
result = string.match(/(^|\W)(#[a-z\d][\w-]*)/ig);
console.log(result)
Results in:
["#foo", " #bar"]
Notice the whitespace in #bar.
What should I change to my RegEx to exclude the boundary in the return to .match?
Thanks for the help!!
You don't need (^|\W) before as # is considered non word character anyway. You are getting space because \W will match space also.
This regex would work better:
var re = /(?:^|\s)(#[a-z\d][\w-]*)/g,
matches = [],
input = "#foo #bar abc#baz";
while (match = re.exec(input)) matches.push(match[1].trim());
console.log(matches);
//=> ["#foo", "#bar"]
EDIT: To avoid loops:
var m = [];
var str = "#foo #bar abc#baz";
str.replace(/(^|\s)(#[a-z\d][\w-]*)/g, function($1) { m.push($1.trim()); return $1; } );
console.log(m);
//=> ["#foo", "#bar"]
You need to use this syntax to extract capture groups:
var str = '#foo #bar';
var myRegexp = new RegExp('(?:^|\\W)(#[^\\W_][\\w-]*)', 'g');
var matchResult = myRegexp.exec(str);
var result = Array();
while (matchResult != null) {
result.push(matchResult[1]);
matchResult = myRegexp.exec(str);
}
console.log(result);
If you don't want to loop through the match results, you can use this trick:
var str = '#foo #bar';
var result = Array();
str.replace(/(?:^|\W)(#[^\W_][\w-]*)/g, function (m, g1) { result.push(g1); } );
console.log(result);

Regex to get words between ":" and "," in javascript

I'm learning regex. I'm trying to get the most correct regex for the following :
Input is:
class:first,class:second,subject:math,subject:bio,room:nine
Expected output:
first,second,math,bio,nine
Want to store the above output in a string . var s = "";
Here's what I tried:
(:)(.*)(,)
However I want the last word too.
Using RegExp.prototype.exec:
var re = /:(.*?)(?:,|$)/g; // `,|$` : match `,` or end of the string.
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
var result = [];
var match;
while ((match = re.exec(str)) !== null)
result.push(match[1]);
result.join(',') // => 'first,second,math,bio,nine'
Using String.prototype.match, Array.prototype.map:
var re = /:(.*?)(,|$)/g;
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
str.match(re).map(function(m) { return m.replace(/[:,]/g, ''); }).join(',')
// => 'first,second,math,bio,nine'
Here is another method (based on the request so far):
var str = 'class:first,class:second,subject:math,subject:bio,room:nine';
// global match doesn't have sub-patterns
// there isn't a look behind in JavaScript
var s = str.match(/:([^,]+)(?=,|$)/g);
// result: [":first", ":second", ":math", ":bio", ":nine"]
// convert to string and remove the :
s = s.join(',').replace(/:/g, '');
// result: first,second,math,bio,nine"
Here is the fiddle

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