I have made this script and i have a question:
$(document).ready(function() {
$('html').html(function(i, v) {
var searchMask = "think";
var regEx = new RegExp(searchMask, "ig");
return v.replace(regEx, '<span style="background-color:yellow;">$&</span>');
});
});
<p id="demo">String replace. any Think new replace</p>
This script take a word inside the html like "think" and replace it with a background-color span with the searched word inside.
If you see the fiddle initially "think" had the "T" capital, after the replacement was of course changed to tiny "t". I would like the script to always keep case sensitive, can this be done with js?
I want to be able to change the words by searching them with the tiny ones.
fiddle: http://jsfiddle.net/GHQU6/9/
You could insert the found string with $& into the replacement.
var searchMask = "think",
regEx = new RegExp(searchMask, "ig"),
v = 'THINK, but do not think too much!';
document.body.innerHTML += v.replace(regEx, '<span style="background-color:yellow;">$&</span>');
Because you're replacing with searchMask and searchMask = "think"
Change it to Think. There is an exact word replace is happening.
You can change it to &$ to replace with found word.
return v.replace(regEx, '<span style="background-color:yellow;">$&</span>');
$(document).ready(function() {
$('html').html(function(i, v) {
var searchMask = "think";
var regEx = new RegExp(searchMask, "ig");
return v.replace(regEx, '<span style="background-color:yellow;">$&</span>');
});
});
<p id="demo">String replace. any Think new replace</p>
Related
currently I am very confused! I have been trying to solve this for a while, and can't seem to crack it. I can't even find an answer on Google.
Currently I am using this Regex I wrote in Javascript:
((?: {4,}|\t+)(?:.*))
Simply, it matches everything that is 4+ spaces out or 1+ tabs out in a textarea. Yea, that sounds familiar you say? It is simply what Stack Overflow does for codeblocks. Now, I have run in to an issue.
Basically I am wanting to replace all of these instances found in the textarea, but first I want to back them up to an array. Now, I am not sure how I grab each match found, and insert it in to the array.
Here is what I have so far:
.replace(/((?: {4,}|\t+)(?:.*))/gi, function (m, g1, g2) {
return //STUCK HERE
}); //Matches Bold
So simply, I just want to grab all matches found in a textarea (Either indented or 4 spaces) and then I would like to add the contents of the match to an array.
How would I go about doing this? Please Help!
You can hit two targets with one bullet:
var items = [];
var re = /((?: {4,}|\t+)(?:.*))/g;
textarea.value = textarea.value.replace(re, function ($0, $1) {
items.push($1);
return 'replacement';
});
If you want to get the code blocks back then:
var codeLines = [];
var reMarkers = /\{\{(.*?)\}\}/g;
var reCodeBlocks = /((?: {4,}|\t+)(?:.*))/g;
var text = textarea.value;
// save and remove code blocks
text = text.replace(reCodeBlocks, function ($0, $1) {
var marker = '{{' + codeLines.length + '}}';
codeLines.push($1);
return marker;
});
// revert to previous state
text = text.replace(reMarkers, function ($0, $1) {
return codeLines[parseInt($1, 10)];
});
If you want to get the array of matches, you can use match() function :
var matchesArray = $('textarea').val().match('/((?: {4,}|\t+)(?:.*))/gi');
and if you want to replace, use simple replace() function :
$('textarea').val().replace('/((?: {4,}|\t+)(?:.*))/gi', 'replaceWith');
Hope this helps.
I am trying to create a regular expression in JS which will match the occurences of box and return the full compound word
Using the string:
the box which is contained within a box-wrap has a box-button
I would like to get:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box?
This is what I have tried so far but it does not return the results I desire.
http://jsfiddle.net/w860xdme/
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
Try this way:
([\w-]*box[\w-]*)
Regex live here.
Requested by comments, here is a working example in javascript:
function my_search(word, sentence) {
var pattern = new RegExp("([\\w-]*" + word + "[\\w-]*)", "gi");
sentence.replace(pattern, function(match) {
document.write(match + "<br>"); // here you can do what do you want
return match;
});
};
var phrase = "the box which is contained within a box-wrap " +
"has a box-button. it is inbox...";
my_search("box", phrase);
Hope it helps.
I'll just throw this out there:
(box[\w-]*)+
You can use this regex in JS:
var w = "box"
var re = new RegExp("\\b" + w + "\\S*");
RegEx Demo
This should work, note the 'W' is upper case.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\Wbox\W
It looks like you're wanting to use the match with a regex. Match is a string method that will take a regex as an argument and return an array containing matches.
var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']
We have a string:
var dynamicString = "This isn't so dynamic, but it will be in real life.";
User types in some input:
var userInput = "REAL";
I want to match on this input, and wrap it with a span to highlight it:
var result = " ... but it will be in <span class='highlight'>real</span> life.";
So I use some RegExp magic to do that:
// Escapes user input,
var searchString = userInput.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// Now we make a regex that matches *all* instances
// and (most important point) is case-insensitive.
var searchRegex = new RegExp(searchString , 'ig');
// Now we highlight the matches on the dynamic string:
dynamicString = dynamicString.replace(reg, '<span class="highlight">' + userInput + '</span>');
This is all great, except here is the result:
console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>REAL</span> life.";
I replaced the content with the user's input, which means the text now gets the user's dirty case-insensitivity.
How do I wrap all matches with the span shown above, while maintaining the original value of the matches?
Figured out, the ideal result would be:
// user inputs 'REAL',
// We get:
console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>real</span> life.";
You'd use regex capturing groups and backreferences to capture the match and insert it in the string
var searchRegex = new RegExp('('+userInput+')' , 'ig');
dynamicString = dynamicString.replace(searchRegex, '<span class="highlight">$1</span>');
FIDDLE
You can use it without capturing groups too.
dynamicString = text.replace(new RegExp(userInput, 'ig'), '<span class="highlight">$&</span>');
I am trying to find matching patterns for the string that a user enters in to textbox, i was successful with the code in most cases with my code, bt ive found in some cases, it doesnt return all the needed results. I am attaching a jsfiddle link to show its wrking, I will also paste the code for future references
http://jsfiddle.net/faphf/2/
$("#facetSearchBox").live("keyup",
function() {
$("#test").empty();
facetSearch();
});
function facetSearch(){
var facetSearchTerm = $("#facetSearchBox").val();
facetSearchTerm = facetSearchTerm.toLowerCase();
var inputArray=["mark zuckerberg","ben s bernanke","ben bernanke","sven grundberg", "michael bloomberg","robert powell","kenneth lieberthal","frank boulben"];
var re = new RegExp(facetSearchTerm, "ig");
var outputArray = inputArray.filter(function(item) {
return re.test(item);
});
for(var k=0; k<outputArray.length;k++){
$("#test").append(outputArray[k] + "<br>" );
}
}
Try searching ben, it will not return all the desired results... it would be helpful if you could help me tell what is wrong with the code?
Remove the global modifier g from your Regular expression. It should work fine after that.
var re = new RegExp(facetSearchTerm, "i");
Test Link: http://jsfiddle.net/faphf/5/
EDIT:
Why RegExp with global flag in Javascript give wrong results?
Use:
var re = new RegExp( facetSearchTerm, "i");
See:fiddle
For word boundary matching:
var re = new RegExp("\\b" + facetSearchTerm, "i");
See:fiddle
A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:
aaaaaaaaaaaaaaaaaaaaaaaaa
Should turn in to
aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa
I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks
Here is one option:
string.match(/.{1,10}/g).join("<br/>");
Assuming the text is inside a div or a span:
<div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div>
You can do:
$(function() {
var html=$('#myDiv').html();
var newHtml='';
for (var i=0;i<html.length;i++) {
newHtml=newHtml+html[i];
if ((i+1)%10==0) {newHtml=newHtml+'<br/>';}
}
$('#myDiv').html(newHtml);
});
Here is example: http://jsfiddle.net/68PvB/
Good Luck!
If you have your string in a variable you can use its replace method like this:
var chunklen = 2; //the length of the chunks you require
var str = '123456789'; //your string
var rxp = new RegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9