I need help getting a number from a <p> element with javascript - javascript

I am new in JavaScript. I have 3 numbers with 10 digits in a <p> tag, and I would like to select and convert them to a link. I was able to get the numbers and convert them to link, but I am getting all 3 numbers at the same time as one link, it would be great if I can get some help, Thank you
Here is my code:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '"'+text+'"');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>

You can capture certain expressions in regex. Then you can get value from that group by using $ and a group number. There's only one group so in this case there'll be $1;
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$1";
var rgx = /(\d{10})/g; // () wraps an expression in a group
var text = str.match(rgx);
var res = str.replace(rgx, '$1');
document.querySelector("p").innerHTML = res;
}
More about capturing groups: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
Edit: I found even a simpler way - if you want to refer to the whole expression you don't need to create a group. To insert matched value you can use $&:
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$&";
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '$&');
document.querySelector("p").innerHTML = res;
}

str.match(rgx);
returns an array of matching strings. If you want to use only on item of the array, you can reference to the index (like text[0]) or you can i.e. loop over the array with text.forEach
or you can map over it and generate links like this:
let links = text.map((string) => { return `www.yourlink.com/${string}`})

in your replace statement use text instead of rgx
var res = str.replace(text, '"'+text+'"');
that way you only replace the instance of the matched text instead of all the rgx matches
EDIT
this should do it
function myFunction() {
var str = document.querySelector("p").innerHTML;
var rgx = /\d{10}/g;
var text = str.match(rgx);
for (i=0; i<text.length; i++) {
var link = 'https://www.google.com/search?q='+text[i];
str = str.replace(text[i], '"'+text[i]+'"');
}
document.querySelector("p").innerHTML = str;
}
myFunction();

Related

Slice from sections from URL

Given these URLs:
/content/etc/en/hotels/couver/offers/residents.html
/content/etc/en/offers/purchase.html
I want to remove (slice) from the URL and get only /offers/residents and /offers/purchase
I wrote this code to do it but I'm getting different results than I require. Please let me know which syntax will work as expected.
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(0,5);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(0,5);
One way to achieve this would be to split the strings by / and then only use the last two sections of the path to rebuild a string:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/\.\w+$/, '').split('/');
var output = locs.slice(-2).join('/');
console.log(output);
});
Alternatively you could use a regular expression to only retrieve the parts you require:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/.+\/(\w+\/\w+)\.\w+$/, '$1');
console.log(locs);
});
You could extract the substring that you want with regex. In the example below the matches[1] will contain the wanted substring.
var str = '/content/etc/en/hotels/couver/offers/residents.html';
var matches = str.match(/([\w]+\/[\w]+)\.html/);
var parsed = matches[1];
this is what you meant for?
to change the slice numbers?
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(29,46);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(15,31);
Use regex, to remove everything before and after string, that starts from /offers and ends with .html
const str1 = '/content/etc/en/hotels/couver/offers/residents.html';
const str2 = '/content/etc/en/offers/purchase.html';
const regex = /^(.*)(\/offers\/.*)(.html)$/g;
console.log(str1.replace(regex, '$2')); // /offers/residents
console.log(str2.replace(regex, '$2')); // /offers/purchase
https://regex101.com/r/hRwLHi/1

JS What's the fastest way to display one specific line of a list?

In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));

How to change this regex replace from replacing a single word to replacing an array of words?

I've searched but cannot adapt anything to my code. I'm trying to make var toReplace = "warming" into an array var toReplace = ['global', 'warming'] so it will replace every word from the array in input with var newWord which just wraps the word in a span. thanks for any help!
if (temperature > 90) {
var input = 'ITS GLOBAL EFFING WARMING';
var toReplace = "WARMING";
var emphasisColor = 'cyan';
};
var newWord = `<span style="color: ${emphasisColor}">${toReplace}</span>`;
var regEx = new RegExp(toReplace,"g");
var output = input.replace(regEx, newWord);
join by | to alternate, so that either word in the array will match. Also make sure to use the i flag to make it case-insensitive.
Also put $& in the replacement string to echo the matched string (so that, for example, when GLOBAL is matched, the result is <span style="color: cyan">GLOBAL</span> rather than <span style="color: cyan">global,warming</span>:
var input = 'ITS GLOBAL EFFING WARMING';
var toReplace = ['global', 'warming']
var emphasisColor = 'cyan';
var regEx = new RegExp(toReplace.join('|'),"gi");
var output = input.replace(regEx, `<span style="color: ${emphasisColor}">$&</span>`);
console.log(output);
Of course, this depends on toReplace not having any special characters. If it can have more than just word characters, you might replace-escape them all first.
You could use a forEach to execute a function for each element in the array:
if (temperature > 90) {
var input = "ITS GLOBAL EFFING WARMING";
var toReplace = ["GLOBAL", "WARMING"];
var emphasisColor = "cyan";
};
toReplace.forEach((element, index) => {
regEx = new RegExp(element, "gi");
input = input.replace(regEx, `<span style="color: ${emphasisColor}">${toReplace[index]}</span>`);
});
You can also use a for loop instead of forEach to obtain the same result.
Happy Coding! :)

replace multiple words using javascript?

I am using the following code to replace one word by an empty space in an input field.
however, I want to be able to replace multiple words with empty space.
basically I need to create a word filter so the users can't type certain words.
HTML CODE
<input type="text" id="demo" name="demo" onkeyup="myFunction()" onkeydown="myFunction()" />
Javascript code:
<script>
function myFunction() {
var words = "badword1";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
}
</script>
I've tried something like this:
<script>
function myFunction() {
var words = "badword1 || badword2 || bad word3";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
alert('that word is not allowed!');
}
</script>
but this doesn't work.
first, it doesn't replace any given badword(s) with empty space and second it fires the aler(); message as soon as I type the first letter in the input field!
could someone please help me out with this?
something like this takes the array of bad words... loops through them creates a global regex that then is used to replace it... compares the original and resulting string if they changed put alert.
var badwords = ['badword1','badword2','badword3']; //array of badwords
function myFunction() {
var str = document.getElementById("demo").value;
var res = str;
for (var i = badwords.length - 1; i >= 0; i--) {
var badword = badwords[i];
badWordRegex = new RegExp(badword, 'g');
res=res.replace(badWordRegex, " ");
};
document.getElementById("demo").value = res;
if (str !== res){
alert('that word is not allowed!');
}
}
Use regex:
var words = new RegExp("badword1|badword|bad word3", g);
ACtually you shouldn't trust client-side code...

Javascript string separated by a comma

I'm trying to get everything before/after a comma from a string
var test = 'hello,world';
Result:
var one = 'hello';
var two = 'world';
What would be a good way to this?
Thanks
.split
Extra text because I need to write 15 characters for this submission to be approved.
-- edit
okay, more explicitly:
var k = "a,b".split(",");
alert(k[0]);
alert(k[1]);
var test = 'hello,world',
words = test.split(',');
var one = words[0]; // hello
var two = words[1]; // world

Categories

Resources