How do I replace the html objects with it's text content? - javascript

I'm trying to replace link parameters with the query strings and I'm a noob when it comes to web dev
I've tried String(), object.textContent() and some more things but can't seem to get what I want
here's my code:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",phone); //phone is an input box returned by document.getElementByID() method
link = link.replace("replace2",message); //message is a text area returned by document.getElementByID() method
expected link: https://someWebsite?phone=123456&mesaage=somemessage
actual link: https://someWebsite?phone= [object HTMLInputElement]&message=[object HTMLTextAreaElement]

To get the value of an input, you use its value. Also, in query strings, you must encode query parameters with encodeURIComponent¹. So:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",encodeURIComponent(phone.value));
link = link.replace("replace2",encodeURIComponent(message.value));
Also note that each of those will replace the first occurrence, not all occurrences. See this question's answers if you need to replace each of those (replace1, replace2) in more than just the first place it appears.
Of course, with the code you've shown, it would make more sense not to use replace at all:
link = "https://someWebsite?phone=" + encodeURIComponent(phone.value) +
"&message=" + encodeURIComponent(message.value);
Or with ES2015+:
link = `https://someWebsite?phone=${encodeURIComponent(phone.value)}&message=${encodeURIComponent(message.value)}`;
¹ You have to encode the names, too, but encodeURIComponent("phone") is "phone" and encodeURIComponent("message") is "message", so... But if you had other characters in there, such as [], you'd need to encode them.

In jQuery we use backticks and ${} for string interpolation:
`some text ${replacedtext} some other text`
If you're using vanilla javascript use + signs for string interpolation:
"some text" + replacedtext + "some other text"
Hope this helps

Related

JS RegEx to remove part of a URL?

I am using the GoogleBooks API to search for particular titles by name and retrieve a cover image URL. For example, searching for "The Great Gatsby" will return the following image link:
http://books.google.com/books/content?id=HestSXO362YC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
If you look at the following image, you can see that there is a small fold on the bottom right corner. Some image URLs will have the fold and others won't. If you remove edge=curl from the URL link, the fold is removed.
Is there any way to use a regex to find and delete the curled portion?
Further, is there any way to use regex to change the img=1 value to img=2?
you can use the .replace() method
let URL = "some random URL you have"
console.log(URL.replace('&edge=curl',''))
Will replace every "&edge=curl" that it finds in this string and replace it with '' an empty string which is basically removing it.
You can also use the same method .replace() to replace any static URL variables like "img=1"
console.log(URL.replace('img=1','img=2'))
Don't use regex to parse URLs. Use URL object:
var u = new URL("http://books.google.com/books/content?id=HestSXO362YC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api");
u.searchParams.delete("edge");
u.searchParams.set("img", "2");
console.log(u.href);
To obtain an updated url where the &edge=curl pattern is replaced and the &img= and &zoom= parameters are updated, you could achieve this by chaining multiple .replace() calls as shown below:
const url = "http://books.google.com/books/content?id=HestSXO362YC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
// New values for img and zoom parameters
const img = 300;
const zoom = 22;
console.log(
url
.replace(/&img=(\w+)/,`&img=${img}`)
.replace(/&zoom=\w+/,`&zoom=${zoom}`)
.replace(/&edge=curl/,"")
)
Here the &img= and &zoom= parameters are updated with regular expressions &img=\w+ and &zoom=\w+, where \w+ will match one or more alpha numeric characters that appear after the parameter.
The advantage with this approach (over explicitly specifying img=1 and replacing it with img=2 ) is that you can update those parameter/value substrings of the input url without having to know the actual value of those parameters prior to replacement (ie that img has a value 1).
Note that this approach assumes the parameters being updated are prefixed with & (and not ?).
Hope that helps!
try this
let url = 'http://books.google.com/books/content?id=HestSXO362YC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api';
// remove &edge=curl
url = url.replace('&edge=curl', '');
// replace img=1 with img=2
url = url.replace('img=1', 'img=2');

Is it possible to move substrings to a specific location with RegEx?

Background: I used quill.js to get some rich text input. The result I want is quite similar to HTML so I went with the quill.container.firstChild.innerHTML approach instead of actually serializing the data. But when it comes to anchor, instead of
Anchor
I actually want
Anchor{{link:test.html}}
With .replace() method I easily got {{link:test.html}}Anchor</a> but I need to put the link description after the Anchor text. Is there a way to swap {{link:test.html}} with the next </a> so I can get the desired result? There can be multiple anchors in the string, like:
str = 'This is a test. And another one here.'
I would like it to become:
str = 'This is a test{{link:test1.html}}. And another one{{link:test2.html}} here.'
You could also use dom methods. The dom is a better html parser than regex. This is a fairly simple replaceWith
str = 'This is a test. And another one here.'
var div = document.createElement('div');
div.innerHTML = str;
div.querySelectorAll('a').forEach(a=>{
a.replaceWith(`${a.textContent}{{link:${a.getAttribute('href')}}}`)
})
console.log(div.innerHTML)
Yes, you can use capture groups and placeholders in the replacement string, provided it really is in exactly the format you've shown:
const str = 'This is a test. And another one here.';
const result = str.replace(/<a href="([^"]+)">([^<]+)<\/a>/g, "$2{{link:$1}}");
console.log(result);
This is very fragile, which is why famously you don't use regular expressions to parse HTML. For instance, it would fail with this input string:
const str = 'This is a test <span>blah</span>. And another one here.';
...because of the <span>blah</span>.
But if the format is as simple and consistent as you appear to be getting from quill.js, you can apply a regular expression to it.
That said, if you're doing this on a browser or otherwise have a DOM parser available to you, use the DOM as charlietfl demonstrates;

replacing numbers in a string with regex in javascript

I have string that contains numbers and characters. I want to replace the numbers with another value that will give it a css class of someClass.
Now I got the code to detect all the numbers in the string and replace it with something else.
My question is how do I get the current number match and put it to the new string or value that will replace the original one?
Basically what I want to happen is:
for example, I have this string: 1dog3cat, I want it to get replaced with <span class="someClass">1</span>dog<span class="someClass">3</span>cat
Here's my current code:
var string_variable;
string_variable = "1FOO5,200BAR";
string_variable = string_variable.replace(/(?:\d*\.)?\d+/g, "<span class='someClass'>" + string_variable + "</span>");
alert(string_variable);
Simply remember the matched pattern using parenthesis and retrieve that value using $1 and add span tag to it.
Use this regex
string_variable = string_variable.replace(/(\d+)/g, "<span class='someClass'>$1</span>");
See DEMO

Is there any way for me to work with this 100,000 item new-line separated string of words?

I've got a 100,000+ long list of English words in plain text. I want to use split() to convert the list into an array, which I can then convert to an associative array, giving each list item a key equal to its own name, so I can very efficiently check whether or not a string is an English word.
Here's the problem:
The list is new-line separated.
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
This means that var list = ' <copy/paste list> ' isn't going to work, because JavaScript quotes don't work multi-line.
Is there any way for me to work with this 100,000 item new-line separated string?
replace the newlines with commas in any texteditor before copying to your js file
One workaround would be to use paste the list into notepad++. Then select all and Edit>Line Operations>Join lines.
This removes new lines and replaces them with spaces.
If you're doing this client side, you can use jQuery's get function to get the words from a text file and do the processing there:
jQuery.get('wordlist.txt', function(results){
//Do your processing on results here
});
If you're doing this in Node.js, follow the guide here to see how to read a file into memory.
You can use notepad++ or any semi-advanced text editor.
Go to notepad++ and push Ctrl+H to bring up the Replace dialog.
Towards the bottom, select the "Extended" Search Mode
You want to find "\r\n" and replace it with ", "
This will remove the newlines and replace it with commas
jsfiddle Demo
Addressing this purely from having a string and trying to work with it in JavaScript through copy paste. Specifically the issues regarding, "This means that var list = ' ' isn't going to work, because JavaScript quotes don't work multi-line.", and "Is there any way for me to work with this 100,000 item new-line separated string?".
You can treat the string like a string in a comment in JavaScript . Although counter-intuitive, this is an interesting approach. Here is the main function
function convertComment(c) {
return c.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
It can be used in your situation as follows:
var s = convertComment(function() {
/*
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
*/
});
At which point you may do whatever you like with s. The demo simply places it into a div for displaying.
jsFiddle Demo
Further, here is an example of taking the list of words, getting them into an array, and then referencing a single word in the array.
//previously shown code
var all = s.match(/[^\r\n]+/g);
var rand = parseInt(Math.random() * all.length);
document.getElementById("random").innerHTML = "Random index #"+rand+": "+all[rand];
If the words are in a separate file, you can load them directly into the page and go from there. I've used a script element with a MIME type that should mean browsers ignore the content (provided it's in the head):
<script type="text/plain" id="wordlist">
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
</script>
<script>
var words = (function() {
var words = '\n' + document.getElementById('wordlist').textContent + '\n';
return {
checkWord: function (word) {
return words.indexOf('\n' + word + '\n') != -1;
}
}
}());
console.log(words.checkWord('aaliis')); // true
console.log(words.checkWord('ahh')); // false
</script>
The result is an object with one method, checkWord, that has access to the word list in a closure. You could add more methods like addWord or addVariant, whatever.
Note that textContent may not be supported in all browsers, you may need to feature detect and use innerText or an alternative for some.
For variety, another solution is to put the unaltered content into
A data attribute - HTML attributes can contain newlines
or a "non-script" script - eg. <SCRIPT TYPE="text/x-wordlist">
or an HTML comment node
or another hidden element that allows content
Then the content could be read and split/parsed. Since this would be done outside of JavaScript's string literal parsing it doesn't have the issue regarding embedded newlines.

RegExp - If first part of search string is found then replace with the full search string value

Is there a RegExp to find and replace a value based on the criteria, "if first part of search string is in the target string then replace the part that matches with the search string."
This is a special search and replace because the replacement is also used as the search string.
For example, I have this URL:
http://www.domain.com/path/something/more/something/
Search for any part of the following and replace with the whole:
/path/user/
Since, "/path/" is in both the replacement string and the target string the results would be:
http://www.domain.com/path/user/something/more/something/
NOTE: The search / replacement value can be anything.
I don't know what the replacement and search string is at the time I make a replacement so I can't use something that hard codes the search string. For example, this won't work because the term is hard coded:
s.replace(/(\/path\/)/, "$1value/");
Another example:
Here is the sentence, "Thank you Susan for your order."
Here is the search and replacement, "Susan Summers"
Here is the desired sentence, "Thank you Susan Summers for your order."
Use Case:
Lets say you are given 1 million text documents that are letters to customers but when they created the documents they used the customers first name only when they were supposed to use the full name. Now it's your job to find and replace every occurrence of their first name with their full name. You only have their full name to work with not first name.
Just realized this may not work as a RegEx and might require code.
You can use:
s = 'http://www.domain.com/path/something/more/something/';
r = s.replace(/(\/path\/)/, "$user/");
//=> "http://www.domain.com/path/user/something/more/something/"
You don't need to use regular expression for this case:
var url = 'http://www.domain.com/path/something/more/something/';
url.replace('/path/', '/path/user/');
// => "http://www.domain.com/path/user/something/more/something/"
I'm not quite sure if I understand the problem correctly. The following replaces any part of of /path/user/ (-> part 1: 'path', part 2: 'user') with the whole /path/user:
var url1 = "http://www.domain.com/path/something/more/something/";
var url2 = "http://www.domain.com/user/something/more/something/";
url1.replace(/\/path\/|\/user\//, '/path/user/');
url2.replace(/\/path\/|\/user\//, '/path/user/');
results in:
http://www.domain.com/path/user/something/more/something/
http://www.domain.com/path/user/something/more/something/
I hope this is what you need, otherwise, please add another example.
EDIT:
Here is the regex in action: http://regex101.com/r/jL6tK6
split + join alternative :
url = url.split('/path/').join('/path/user/');
Although your requirements are not clear, here is a guess that raises a few extra questions :
var sub = '/path/user/';
var parts = sub.match(/[^\/]+/g);
url = url.replace(new RegExp(
'\\/(' + [parts.join('\\/')].concat(parts).join('|') + ')\\/'
), sub);
The resulting regular expression is as follows :
/\/(path\/user|path|user)\// // "/path/user/" OR "/path/" OR "/user/"
Let's check some urls assuming we live in the best of worlds :
'http://domain/' -> 'http://domain/'
'http://path/user/' -> 'http://path/user/'
'http://path/' -> 'http://path/user/'
'http://user/' -> 'http://path/user/'
Now, what do you think about the following ones?
'http://path/user' -> 'http://path/user/user'
'http://user/path/' -> 'http://path/user/path/'
'http://path/user/path/' -> 'http://path/user/path/'
The remaining questions are :
Is this what you are looking for?
What to do when there is no trailing slash?
What to do in the reverse order case?
What to do with recurrent parts?

Categories

Resources