Javascript Regex - Insert word (hit) - javascript

is it possible to insert the word that was found into the replace ?
$(function() {
content = 'hallo mein name ist peter und ich komme aus berlin. Und du?';
words = 'mein na,berlin'
words = words.replace(/,/,'\|');
words = words.replace(/\s/,'\\s');
regex = new RegExp(words,'gi');
content = content.replace(regex,'<strong>*insert here the word that was found*</strong>');
alert(''+content+'');
});
working example
http://www.jsfiddle.net/V9Euk/227/
Thanks in advance!
Peter

Try this:
content.replace(regex,'<strong>$&</strong>');
$& is replaced with the full match.
Working example: http://www.jsfiddle.net/V9Euk/228/
If you are more comfortable with it, you can add a group and replace it with $1 (this one will raise less questions):
words = words.replace(/,/g,'\|');
words = words.replace(/\s/g,'\\s');
words = '(' + words + ')';
regex = new RegExp(words, 'gi');
content = content.replace(regex,'<strong>$1</strong>');
Note that you probably want the g flag on these replaces, or you only change the first space and comma.
If you also want to avoid partial matching (so "mein na" doesn't capture), add \b:
words = '\\b(' + words + ')\\b';

Related

Find first word in a string after a . in javascript

I am working on a school assignment where we have to highlight the first word after a "." in a text with the press on a button.
As far as i've come I have created a HTML page, the HTML page contains a button and on click it is supposed to highligt the first word after a "." I have discovered that I probably have to use split and or slice.
function highligtWord(){
var tekst = document.getElementById("tekst").innerHTML;
for (var i = 0 ; i < tekst.length; i++) {
var arr = tekst.split(". ")[i].split(" ")[0]
console.log(arr)
var res = tekst.replace(`${arr}`, "<span style=background-color:yellow>" + `${arr}` + "</span>" );
document.getElementById("tekst").innerHTML += res;
}
So far this does not work as intended as it "highlight" words that aren't after a "." so my question is, what do i do wrong?
And how can I get you "highligt" all words after a "." instead?
Thanks in advance
It'd probably be easier to use a regular expression - match \. (a literal dot), then match \S+ - one or more non-space characters. Then replace with the non-space characters surrounded by the highlight span:
const elm = document.getElementById("tekst");
elm.innerHTML = elm.innerHTML.replace(
/(\. *)(\S+)/,
'$1<span style=background-color:yellow>$2</span>'
);
<div id="tekst">foo bar. baz should be highlighted.</div>
If you want to highlight all words that follow a ., use the global flag instead for the regular expression (use /g).

jQuery autocomplete RegExp for highlight words [duplicate]

I have this function that finds whole words and should replace them. It identifies spaces but should not replace them, ie, not capture them.
function asd (sentence, word) {
str = sentence.replace(new RegExp('(?:^|\\s)' + word + '(?:$|\\s)'), "*****");
return str;
};
Then I have the following strings:
var sentence = "ich mag Äpfel";
var word = "Äpfel";
The result should be something like:
"ich mag *****"
and NOT:
"ich mag*****"
I'm getting the latter.
How can I make it so that it identifies the space but ignores it when replacing the word?
At first this may seem like a duplicate but I did not find an answer to this question, that's why I'm asking it.
Thank you
You should put back the matched whitespaces by using a capturing group (rather than a non-capturing one) with a replacement backreference in the replacement pattern, and you may also leverage a lookahead for the right whitespace boundary, which is handy in case of consecutive matches:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word + '(?=$|\\s)'), "$1*****");
return str;
};
var sentence = "ich mag Äpfel";
var word = "Äpfel";
console.log(asd(sentence, word));
See the regex demo.
Details
(^|\s) - Group 1 (later referred to with the help of a $1 placeholder in the replacement pattern): a capturing group that matches either start of string or a whitespace
Äpfel - a search word
(?=$|\s) - a positive lookahead that requires the end of string or whitespace immediately to the right of the current location.
NOTE: If the word can contain special regex metacharacters, escape them:
function asd (sentence, word) {
str = sentence.replace(new RegExp('(^|\\s)' + word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '(?=$|\\s)'), "$1*****");
return str;
};

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

How can I transfer every line which starts with specific patterns to the end of the string?

I have a string like this:
var str = " this is a [link][1]
[1]: http://example.com
and this is a [good website][2] in my opinion
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg
[![this is a photo][3]][3]
and there is some text hare ..! ";
Now I want this:
var newstr = "this is a [link][1]
and this is a [good website][2] in my opinion
[![this is a photo][3]][3]
and there is some text hare ..!
[1]: http://example.com
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg"
How can I do that?
In reality, that variable str is the value of a textarea ... and I'm trying to create a markdown editor .. So what I want is exactly the same with what SO's textarea does.
Here is my try:
/^(\[[0-9]*]:.*$)/g to select [any digit]: in the first of line
And I think I should create a group for that using () and then replace it with \n\n $1
try this:
strLinksArray = str.match(/(\[\d+\]\:\s*[^\s\n]+)/g);
strWithoutLinks = str.replace(/(\[\d+\]\:\s*[^\s\n]+)/g, ''); //removed all links
Here you will get links as array and string without links then do whatever changes you want.
You can use
var re = /^(\[[0-9]*]:)\s*(.*)\r?\n?/gm; // Regex declaration
var str = 'this is a [link][1]\n[1]: http://example.com\nand this is a [good website][2] in my opinion\n[2]: http://goodwebsite.com\n[3]: http://example.com/fsadf.jpg\n[![this is a photo][3]][3]\nand there is some text hare ..!';
var links = []; // Array for the links
var result = str.replace(re, function (m, g1, g2) { // Removing the links
links.push(" " + g1 + " " + g2); // and saving inside callback
return ""; // Removal happens here
});
var to_add = links.join("\n"); // Join the links into a string
document.getElementById("tinput").value = result + "\n\n\n" + to_add; // Display
<textarea id="tinput"></textarea>
See regex demo at regex101.com.
Regex explanation:
^ - start of line (due to the /m modifier)
(\[[0-9]*]:) - Group 1 (referred to as g1 in the replace callback) matching...
\[ - opening square bracket
[0-9]* - zero or more digits
] - closing square bracket
: - a colon
\s* - zero or more whitespace
(.*) - Group 2 matching (g2) zero or more characters other than newline
\r?\n? - one or zero \r followed by one or zero \n
/gm - define global search and replace and ^ matches line start instead of string start

Select Random Words From Tag, Wrap In Italic

I have a bunch of dynamically generated H1 tags.
I want to randomly select 1 word within the tag, and wrap it in italic tags.
This is what I have so far, the problem is, it is taking the first h1's dynamically generated content, and duplicating it to every h1 on the page.
Other than that, it works.
Any ideas?
var words = $('h1').text().split(' ');
// with help from http://stackoverflow.com/questions/5915096/get-random-item-from-array-with-jquery
var randomWord = words[Math.floor(Math.random()*words.length)];
// with more help from http://stackoverflow.com/questions/2214794/wrap-some-specified-words-with-span-in-jquery
$('h1').html($('h1').html().replace(new RegExp( randomWord, 'g' ),'<i>'+randomWord+'</i>'));
My ultimate goal
<h1>This is a <i>title</i></h1>
<h1><i>This</i> is another one</h1>
<h1>This <i>is</i> the last one</h1>
All of the titles will be dynamically generated.
http://codepen.io/anon/pen/uskfl
The problem is $('h1') creates a collection of all of the h1 tags in the page.
You can use a function callback of the html() method which will loop over every h1 and treat them as separate instances
$('h1').html(function(index, existingHtml) {
var words = existingHtml.split(' ');
var randomWord = words[Math.floor(Math.random() * words.length)];
return existingHtml.replace(new RegExp(randomWord, 'g'), '<i>' + randomWord + '</i>');
});
see html() docs ( scroll 1/2 way down page, function argument was not in earlier versions)
You can use jQuery's .each() to iterate through the h1s.
$('h1').each(function(){
var words = $(this).text().split(' ');
var randomWord = words[Math.floor(Math.random()*words.length)];
$(this).html(
$(this).html().replace(new RegExp( randomWord, 'g'),'<i>'+randomWord+'</i>')
);
});
Demo: http://jsfiddle.net/RT25S/1/
Edit: I just noticed a bug in my answer that is also in your question and probably in the other answers.
In titles like this is another one, is is italicised in both is and this. scrowler commented that when the selected word is in the title multiple times all of them will be italicised, but I doubt you intended for partial words to be italicised.
The fixes are relatively simple. Just check for spaces before and after the word. You also have to allow for words at the beginning and end of the title using the ^ and $ metacharacters.
Ideally we could use \b, which is a "word boundary", instead but it doesn't seem to work when words end with non-alphanum characters.
You should also probably escape the randomly-selected word before including it in a regex in case it contains any special characters. I added the escaping regex from Is there a RegExp.escape function in Javascript?.
The updated code:
$('h1').each(function(){
var words = $(this).text().split(' ');
var randomWord = words[Math.floor(Math.random()*words.length)];
// Escape the word before including it in a regex in case it has any special chars
var randomWordEscaped = randomWord.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
$(this).html(
$(this).html().replace(
//new RegExp( '\\b' + randomWordEscaped + '\\b', 'g' ),
new RegExp( '(^| )' + randomWordEscaped + '( |$)', 'g' ),
'<i> ' + randomWord + ' </i>'
)
);
});
And the updated JSFiddle: http://jsfiddle.net/RT25S/3/
Note that I added spaces after and before the <i> tags because the regex now captures them. (This still works for words at the beginning/ends of titles because HTML ignores that whitespace.)

Categories

Resources