How to find all regex match in a string - javascript

This might be too simple to find on web but I got problem with finding the answer.
I get string as http response text that contain substrings I want to grab all one by one to further process. Its relative URL.
for example:
var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png separated by some html div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";
var re = new RegExp("[a-z]{5,10}[0-9].png");
var match = re.exec(string)
WScript.Echo (match);
This gives first match. I want to get all collection one by one. I am using Jscript. I am new to javascript.
After the answer I tried this.
var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png separated by some html div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";
var re = new RegExp("[a-z]{5,10}[0-9].png", "g");
var match = re.exec(string)
WScript.Echo (match);
But no luck.

use 'g' for a global search and match to get all matches:-
var string = "div classimage a hrefstring1.png img idEMIC00001 he19.56mm wi69.85mm srcstring1.png separated by some html div classimage a hrefstring2.png srcstring2.png div separated by some html many such relative urls";
var re = new RegExp("[a-z]{5,10}[0-9].png", 'g');
var matches = string.match(re);
for(var i = 0; i < matches.length; i++){
console.log(matches[i]);
}

This should fix your problem :
var re = new RegExp("[a-z]{5,10}[0-9].png", "g");
The "g" stands for global, it'll match all occurrences in your string

just make it
var match = string.match(re)
instead of
var match = re.exec(string);
rest of the code seems to be fine.

Related

JavaScript get first name and last name from string as array

I have a string that has the following format: <strong>FirstName LastName</strong>
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
How can I produce ["firstName", "lastName"] for any string with that format?
In order to parse HTML, use the best HTML parser out there, the DOM itself!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
EDIT
As #RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
However, both methods work perfectly fine; it all comes down to preference.
Just match everything between <strong> and </strong>.
var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\/strong>/);
console.log(matches[1].split(' '));
The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.
let str = '<strong>FirstName LastName</strong>';
let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);
console.log(first, last);
/<[/\w\s-]+>|\s/g
Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].
this is my approach of doing your problem. Hope it helps!
var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");
Edit: it will only work for this specific example.
Another way to do this in case you had something other than an html
var string = "<strong>FirstName LastName</strong>";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space
console.log(string);

Insert line break every 3 lines in javascript?

Hi I'm still a newbie at javascript so I want to create a script that inserts a line break after every 3 lines. So here's my code I got so far
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.toString().match(/.{3}/g).join('</br>');
console.log(newNum);
It is doing it wrong. It seems to be inserting every 3characters instead of lines. Can anyone help me fix the code?
You can use the replace function. Try the below code.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/(.*\n.*\n.*\n)/g, '$1<br>');
console.log(newNum);
EDIT
I have made a few changes to the RegEx in the code below. This will allow you to specify the number of lines between which <br> need to be added.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var newNum = num.replace(/((.*\n){3})/g, '$1<br>');
console.log(newNum);
In the above RegEx, the .* will match all characters till the end of line and the \n will match the new line character.
(.*\n){3}
I have enclosed this in parenthesis to mark it as a group and used {3} to indicate that the preceding group repeats 3 times.
((.*\n){3})
Then the whole RegEx is enclosed in a parenthesis to use it as the first matched group that can be referenced in the replace section using $1.
You can replace the {3} with any number.
You should avoid using string manipulation when using HTML string. Also using BR to break line is not a good idea as well. You should use a block element instead.
var num = `http://url.com
http://url2test.com
http://url3nag.com
http://url4lalala.com
http://url5papapapapa.com
http://url6ddadadadad.com
http://url7etet.com
http://url8testtest.com`;
var content = document.querySelector('.content');
var urls = num.split('\n');
var temp;
for(var i = 0; i< urls.length; i++) {
if(!temp || (i+1) % 3 === 0) {
if (temp) content.appendChild(temp);
temp = document.createElement('div');
}
var span = document.createElement('span');
span.classList.add('link')
span.innerHTML = urls[i];
temp.appendChild(span);
}
content.appendChild(temp);
.link {
margin: 5px;
}
<div class='content'>
Reference:
Is it sometimes bad to use <BR />?

Javascript-Add style to the first value matched in an array and discard the others

I searched through the online resources i found for this particular quest, but im stuck with something that i couldn't get help through them.
I'm trying to find a way to add style to the first matched letter in an array and discard the remaining matched letters.eg say I have a search string called: "disabledDouble". I use the split() method on the string to separate the matched element from the unmatched ones:
search: function(){
var search = "d";
var string = "disabledDouble";
var regex = new RegExp("(" + search + ")", "gi");
var segments = string.split(regex); //o/p :["d", "isable", "d","D","ouble"]
return (
//styled element <span>
)
}
now i want to just add style to the first 'd' in the array (not worry about the second or third 'd's') and join the remaining string such that o/p becomes:
disabledDouble
similarly since the string is dynamically created I've values like:
showStability
accessValues
In all the above cases I'd like to add style only to the first matched value.
any ideas???
You can use replace
var search = "d";
var string = "disabledDouble"
var regex = new RegExp(search, "i");
console.log(string.replace(regex, function(a) {return "<span>" + a + "</span>";}));
Suppose, you want to change the first character only.
var string = 'abracadabra';
console.log(string.replace(/./, '<strong>$&</strong>'));

JavaScript/jQuery manipulate and then replace all links in my HTML content

I am trying to write a script that, after the page load, will replace all my existing links with links in a different format.
However, while I've managed to work out how to do the link string manipulation, I'm stuck on how to actually replace it on the page.
I have the following code which gets all the links from the page, and then loops through them doing a regular expression to see if they match my pattern and then if they do taking out the name information from the link and creating the new link structure - this bit all works. It's the next stage of doing the replace where I'm stuck.
var str;
var fn;
var ln;
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
str = links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi);
if (links[i].href.match(/\/Services\/(.*?)\/People\/(.*?(?=\.aspx))/gi)) {
var linkSplit = links[i].href.split("/");
// Get the last one (so the .aspx and then split again).
// Now split again on the .
var fileNameSplit = linkSplit[linkSplit.length-1].split(".");
var nameSplit = fileNameSplit[0].split(/(?=[A-Z])/);
fn = nameSplit[0];
ln = nameSplit[1];
if(nameSplit[2]){
ln += nameSplit[2];
}
// Build replacement string
var replacementUrl = 'https://www.testsite.co.uk/services/people.aspx?fn='+fn+'&sn='+ln;
// Do the actual replacement
links[i].href.replace(links[i].href, replacementUrl);
}
I've tried a couple of different solutions to make it do the actual replacement, .replace, .replaceWith, and I've tried using a split/join to replace a string with an array that I found here - Using split/join to replace a string with an array
var html = document.getElementsByTagName('html')[0];
var block = html.innerHTML;
var replace_str = links[i].href;
var replace_with = replacementUrl;
var rep_block = block.split(replace_str).join(replace_with);
I've read these, but had no success applying the same logic:
Javascript: How do I change every word visible on screen?
jQuery replace all href="" with onclick="window.location="
How can I fix this problem?
It's simpler than that:
links[i].href = replacementUrl;

Search and Replace with JS: RegExp that does not include html code

I'm looking for a regexp that matches to strings in html body but does not influence strings that appear in title tags e.g. I have:
words = new Array("Android","iOS");
change = new Array ("http://www.google.com","http://www.apple.com");
obj = document.getElementsByTagName("body")[0];
// search and replace
for (i in words) {
re = new RegExp("\\b("+words[i]+")\\b", "ig");
str = obj.innerHTML.replace(re,'$1');
document.getElementsByTagName("body")[0].innerHTML = str;
}
}
So I have a list with words an the JS is replacing these words (eg replacing iOS' by <a href='http://www.apple.com'>iOS</a>) from HTML Body. But: it also replaces HTML Code like '<title = 'iOS'> -> this becomes <title='a href='http://www.apple.com'>iOS</a>' . How can the regexp can be changed that <title='...> and stuff are not changed
Adam
Use a look-ahead to ensure the target is not within a tag (ie the next angle bracket is a <):
re = new RegExp("\\b(" + words[i] + ")\\b(?=[^>]*<)", "ig");

Categories

Resources