regular expression for [allchars] - javascript

I am trying to match something like [allchar] with a regular expression and be able to pull it out and replace it with other content
Here is what I am trying
var text = "[abc123.;.] this is more content";
var replacewith = "[contentreplacedwith]";
reg = new RegExp("/\[{1}.*?\]{1}/g");
if(reg.test(text))
{
txt = $('#message').val().replace(text,'[' + replacewith + ']');
console.log(txt);
}
The result should be
[contentreplacedwith] this is more content

reg = new RegExp("\\[.*?\\]", "g");
x = "[abc123.;.] this is more content";
console.log(x.replace(reg, "[contentreplacedwith]"));
If you use RegExp constructor the there's no need to pass / delimiters and the options like g for global are a second argument.

Related

Add html tags inside a replace method of js(no Jquery)

I'm using the replace method of js to replace a value to style it differently.
style() {
var name = "StackoverFlow";
var value = "Flow";
var regex = new RegExp("(" + value + ")", "gi");
return "<span>"+name.replace(regex, "<strong>$1</strong>")+"</span>"; //replacing the value "Flow" with bold.
}
but instead it returns: Stackover<strong>Flow</strong>.
how can i parse it using the html() instead of plain text and render: StackoverFlow
I'm not sure how you are setting the return value of the function to the document. However, the function I do believe you are looking for is: element.innerHTML.
Example
var element = document.getElementById('myelement');
element.innerHTML = "stack<strong>flow</strong>" //outputs flow in bold text.
Suggestion
<!-- in html -->
<p id="your_element_id"></p>
.
//js
var element = document.getElementById('your_element_id');
element.innerHTML = style();
function style() {
var name = "StackoverFlow";
var value = "Flow";
var regex = new RegExp("(" + value + ")", "gi");
return "<span>"+name.replace(regex, "<strong>$1</strong>")+"</span>";
}

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

Replace string in javascript

I have this string:
1<div>2</div><div>3</div><div>4</div>
if i replace the values
var descriptionVal = desc.replace('<div>', '-').replace('</div>', '-');
it will replace only the first div
1-2</div><div>3</div><div>4</div>
how to replace all div?
You have to use regular expressions to replace. You can use the replace function with global flag g. Checkout the following solution:
var descriptionVal = desc.replace(/<div>/g, '-').replace(/<\/div>/g, '-');
Working example:
var str = "1<div>2</div><div>3</div><div>4</div>";
str = str.replace(/<div>/g, '-').replace(/<\/div>/g, '-');
document.write(str);
With a simple string replace, like your example, only the first occurance of each replace function will be replaced:
var str = "1<div>2</div><div>3</div><div>4</div>";
str = str.replace('<div>', '-').replace('</div>', '-');
document.write(str);

Replace *variable* text but keep case

I need to replace some text in a javascript variable without losing case, ie.
"MAT" ==> "MATch string in db" instead of "Mat" ==> "match string in db"
Right now I'm doing this (doesn't keep the original case):
var user_str = $("#user-input").val();
var db_match = db_match.replace(new RegExp(user_str, "ig") , '<span class="u b match">' + user_str + '</span>');
I found cases where people needed to replace static text, but in my case I need to replace variable content instead.
Obviously this doesn't work either:
var user_str = $("#user-input").val();
db_match = db_match.replace(/(user_str)/ig, "<span class=u b match>$1</span>");
Any idea how to do this?
Use a group and build the regular expression
var str = "test";
var text = "Test this";
var re = new RegExp("(" + str + ")","gi");
console.log(text.replace(re, "<span>$1</span>")) //"<span>Test</span> this"

variable in regular expression not working in jquery

I want to use variable in expression for auto increment id on add more. but when I add variable in expression it won't work and when I statically enter string "_1" in expression it work Here is code
$(document).ready(function() {
var row_number_current = 1;
var row_number_increment = Number(row_number_current);
row_number_increment += 1;
var addMore = '<div id="data_box_1"><label for="chart-pie-text_1">Chart Text</label></div>';
var row1 = addMore.replace("/_"+row_number_current+"/g", '_'+row_number_increment);
var row2 = addMore.replace(/_1/g, '_'+row_number_increment);
alert(row1);
alert(row2);
});
result of row1 is
<div id="data_box_1"><label for="chart-pie-text_1">Chart Text</label></div>
and row2 result is
<div id="data_box_2"><label for="chart-pie-text_2">Chart Text</label></div>
"/_"+row_number_current+"/g" is a string, not a regex. You need to construct a regex using this string, then pass that as the pattern argument in replace:
var regex1 = new RegeExp("_"+row_number_current,"g");
var row1 = addMore.replace(regex1, '_'+row_number_increment);
In your particular case, however, you don't really need a regex. Just use a string:
var row1 = addMore.replace(row_number_current, row_number_increment, "g");
In order to use variables in regular expressions, you have to create new RegExp object and pass your expression as the first string argument:
var regex = new RegExp("_" + row_number_current, "g");
row1 = addMore.replace(regex, "_" + row_number_increment);

Categories