Are there any string replace methods that will replace anything between 2 positions, i.e. range.
When a user highlights a string of text in a textarea I'm able to get the start and end position. I now want to replace that text that's highlighted.
You can use substrings:
var newString =
originalString.substring(0, startIndex) +
myReplacementString +
originalString.substring(endIndex);
You could also use regex:
var rx = new RegExp('^([\\s\\S]{' + startIndex + '})[\\s\\S]{' + (endIndex - startIndex) + '}([\\s\\S]*)$');
var newString = originalString.replace(rx, '$1' + myReplacementString + '$2');
... but I would prefer substrings, in this scenario.
Related
I'm very new to js and programming, and i'd appreciate some help.
Suppose I have the following array (It is a single element array, they are not seperate elements)
var array =
[
'Foo\n' +
'bar23123\n' +
'barbarfoo\n' +
'foo, bar foo\n' +
'foo\n' +
'\n' +
'\n' +
'Bar\n' +
'\n' +
'\n'
]
Assuming there are multiple elements in the array, how can I write a regex expression to count and match the number of literal '\n' in between Foo\n and Bar\n in each element.
I wrote a partial solution to iterate through and return the count of all \n but how do I narrow my search to only return the values in between the two strings?
Here is the code:
let slashN = [];
for(let slash of array){
var reg = RegExp('\\n' , 'g')
slashN.push(slash.match(reg).length)
}
console.log(slashN);
I get the correct count, but I want to refine the regex expression.
Any help is highly appreciated.
You may use
var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs;
See the regex demo. Details:
(?<=Foo\n.*?) - a positive lookbehind that matches a location that is immediately preceded with Foo + newline and then any 0 or more chars, as few as possible
\n - a newline
(?=.*?Bar\n) - a positive lookahead that matches a location immediately followed with any 0+ chars as few as possible and then Bar + newline.
JavaScript demo:
var array =
[
'Foo\n' +
'bar23123\n' +
'barbarfoo\n' +
'foo, bar foo\n' +
'foo\n' +
'\n' +
'\n' +
'Bar\n' +
'\n' +
'\n'
];
let slashN = [];
for(let slash of array){
var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs;
slashN.push(slash.match(reg).length)
}
console.log(slashN);
I have this strange issue, hope that someone will explain what is going on.
My intention is to capture the textual part (a-z, hyphen, underscore) and append the numeric values of id and v to it, underscore separated.
My code:
var str_1 = 'foo1_2';
var str_2 = 'foo-bar1_2';
var str_3 = 'foo_baz1_2';
var id = 3;
var v = 2;
str_1 = str_1.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
$('#test').html(str_1 + '<br>' + str_2 + '<br>' + str_3 + '<br>');
Expected result:
foo3_2
foo-bar3_2
foo_baz3_2
Actual Result:
foo3_2_2
foo-bar3_2_2
foo_baz3_2_2
Any ideas?
JS Fiddle example
Your pattern:
/([a-z_-]+)\d+/
matches only "foo1" in "foo1_2", and "foo" will be the value of the captured group. The .replace() function replaces the portion of the source string that was actually matched, leaving the remainder alone. Thus "foo1" is replaced by "foo3_2", but the original trailing "_2" is still there as well.
If you want to alter the entire string, then your regular expression will have to account for everything in the source strings.
Just try with:
str_1 = str_1.match(/([a-z_-]+)\d+/)[1] + id + '_' + v;
Use this instead to capture 1_2 completely:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d+/,'$1' + id + '_' + v);
Because you want to replace _2 also of string. Solution can be this:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
DEMO
Your pattern actually includes the first digits, but it will store only the textual part into $1:
foo1_2
([a-z_-]+)\d+ = foo1
$1 = foo
The pattern stops searching at the first digits of the string.
if you want to replace any characters after the textual part, you could use this pattern:
/([a-z_-]+)\d+.*/
This is my js code:
html = html.replace("/["+increment+"]/gi", '[' + counter + ']');
where increment is 0 and counter is 1
or
html = html.replace("/[0]/gi", '[1]');
My version does not replace the [0] with [1] in my string. Why ?
You need to use the RegExp constructor as the regex is dynamic
var regex = new RegExp("\\[" + increment + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');
Also you could sanitize the dynamic variable if you want
if (!RegExp.escape) {
//A escape function to sanitize special characters in the regex
RegExp.escape = function (value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
//You could also escape the dynamic value it is an user input
var regex = new RegExp("\\[" + RegExp.escape(increment) + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');
Use this way:
html = html.replace(new RegExp("\\["+increment+"\\]", "gi"), '[' + counter + ']');
This makes use of the dynamic values.
I have a jquery code that trims the leading and trailing character (passed from the calling program). I am using a variable in RegExp to replace the character with blank. How can I make the RegExp work for any character passed from the calling program? Here is the simplified code:
var time = ":1h:45m:34s:";
var chr= ':'; //can have . or , or any other character
var regex = new RegExp("(^" + chr + ")|(" + chr+ "$)" , "g"); //works for colon but not for dot.
//var regex = new RegExp("(^/" + chr + ")|(/" + chr+ "$)" , "g"); //for dot I added / but not for colon.
var formattedtime = time.replace(regex, "");
Expected Outputs:
1. time = ":1h:45m:34s:";
chr = ":";
Output: 1h:45m:34s
2. time = "1h:45m:34s";
chr = ":";
Output: 1h:45m:34s
3. time = ".45m.34s";
chr = ".";
Output: 45m.34s
4. time = "1h.45m.34s.";
chr = ".";
Output: 1h.45m.34s
How can I make the regexp work for any character?
You need to escape meta characters (like . and several others) to get literals. You do that by adding a backslash before them.
JS doesn't have any built in function for that, so you could use this:
function quotemeta(str){
return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}
Used like so:
new RegExp("^(?:" + quotemeta(chr) + ")+|(?:" + quotemeta(chr) + ")+$" , "g");
var chr= ':/';
...
var regex = new RegExp("(^[" + chr + "])|([" + chr+ "]$)" , "g");
Regex should this way:-
For Colon, /^(\:)|(\:)$/gim
For Dot, /^(\.)|(\.)$/gim
OR
/^(\:|\w|\.)|(\:|\w|\.)$/gim
LIVE DEMO
I've got a pattern to find matches in a querystring:
'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test')
What I'd like to be able to do is use variable values as the param to match like:
'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test')
[edit] Here's the context in how the code is being used:
GetSrcParam: function(key, value) {
var newSrc = $(this._image).attr('src'),
pattern = '(' + key + '=)([^&]*)';
if (newSrc.match(pattern) == null)
newSrc += '&' + key + '=' + value;
else
newSrc = newSrc.replace(newSrc, '$1' + value);
return newSrc;
}
But it's not working as intended - can anyone help?
If you choose to construct a regex from a string, you need to drop the delimiters (but then you need to double any backslashes, if your regex were to contain any). Try
myregex = new RegExp('(' + key + '=)([^&]*)')
'url.com/foo/bar?this=that&thing=another'.replace(myregex, '$1test')
Are you aware that this would also match thing=another in url.com/foo/bar?something=another? To avoid this, add a word boundary anchor:
myregex = new RegExp('(\\b' + key + '=)([^&]*)')