This question already has answers here:
The .replace() method does change the string in place [duplicate]
(3 answers)
Closed 2 years ago.
(this question is the continuation of my previous question : "how to find private char utf8 in a text?")
I need to replace each match with its value (which is stored in a map) but I have tested several things, including this one (below) but it does not work. I probably don’t have the hindsight to find the solution. I’ve been on for an hour. I probably did a big mistake sorry for that.
Here's my code:
const regex = /[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;
var map = new Map();
//set example values in the map
map.set("", 'something1');
map.set("", 'something2');
map.set("", 'something3');
map.set("", 'something4');
const str = "\u{f0001} lorem ipsum \u{f0002} dolor sit amet \u{f0003}\n consectetur adipiscing elit\u{f0004}\sed do eiusmod tempor</"; // my text
console.log(str);
var tab = str.match(regex).map(x => Array.from(x)
.map((v) => v.codePointAt(0).toString(10))
.map((hex) => "0000".substring(0, 4 - hex.length) + hex))
for(var i = 0 ; i < tab.length ; i++){
str.replace(/[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u, map.get("&#"+tab[i][0]+";"));
}
console.log(str); //nothing change
strings are immutable, no method or operators will change them.
in your for loop you should reassign str to the result of str.replace, I think that's all 🙂
for(var i = 0 ; i < tab.length ; i++){
str = str.replace(/[\uE000-\uF8FF\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u, map.get("&#"+tab[i][0]+";"));
}
note that you don't have the 'g' flag on this regex, not sure if this is intended
Edit: as Wiktor pointed out, you will have to switch your declaration from const to let
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i am trying to find some regex which will replace part of a string with html tags. Part of String which should get replaced looks like this:
lorem Google=https://google.com ipsum
Excpected output: lorem Google ipsum
P.S i'm using reactjs
var string = "Google=https://google.com";
var regex = /(\w*)=(https?\:\/\/\w*\.\w*)/gm;
var regexResult = regex.exec(string);
var newAtag = document.createElement('a');
newAtag.href = regexResult[2];
newAtag.innerHTML = regexResult[1];
console.log(newAtag);
document.body.appendChild(newAtag);
Updated based on your comment how to do it if the string is "lorem Google=https://google.com ipsum" basically exactly the same as above. Just don't touch anything before and after the matching regex part. See this:
var element = document.querySelector('div');
var string = element.innerHTML;
var regex = /(\w*)=(https?\:\/\/\w*\.\w*)/gm;
var regexResult = regex.exec(string);
var newAtag = document.createElement('a');
newAtag.href = regexResult[2];
newAtag.innerHTML = regexResult[1];
console.log(newAtag);
element.innerHTML = string.replace(regex, newAtag.outerHTML);
<div>lorem Google=https://google.com ipsum</div>
try this
const ch = "Google=https://google.com"
const makeUrl = ch => {
const [name, url] = ch.split(/=/)
return `${name}`
}
console.log(makeUrl(ch))
You can use the link function of javascript, It will work fine and much mere readable
const link = "Google=https://google.com"
const generateLink = link => {
const [name, url] = link.split(/=/)
return "Google".link(url)
}
console.log(generateLink (link))
I suggest using a tool like RegEx101 to create and test the RegEx:
https://regex101.com
JavaScript example
var str=`# Expect (partially) valid
lorem Google=https://www.google.com ipsum
lorem Google=http://google.com
https://google.com
Long text with linebreaks - http://test.test with many links http://test.test
xxx http://test.TEST xxx https://www.subdomain.google.com.
# Correctly matched yet wrong URLs
https://www.google
# Expect invalid
http://googlecom
htt://google.com
xxx`;
var regEx = /https?:\/\/((\w+\.){1,2})?(\w+\.)\w+/gi;
var result = str.match(regEx);
console.log(result);
This will give you an array with all matched URLs that you then can easily replace with HTML tags.
The RegEx pattern is designed to work with common URLs, yet I did not test it with more complex patterns. It still should be good enough for practical use.
Pattern explained
Match either http/https
Check for 0-2 subdomains (e.g. www.domain, www.subdomain.domain)
Check for domain name
This question already has an answer here:
javascript replace with submatch as array index
(1 answer)
Closed last year.
I'm new to JavaScript and I'm working on an application that have something like that in a string format
"lorem ipsum dolor {#variable#} sit amet {#variable2#}"
How to remove {# and #} and replace the word variable with value and for the second replaces the word variable2 and replaces it with value2
I really appreciate the help.
Thank you in advance
You could use the regex {#(.*?)#} to find the substrings you want to replace. Then, use a map object to get the corresponding value for the captured variable:
let str = `lorem ipsum dolor {#variable#} sit amet {#variable2#}`
let map = {
variable: "value1",
variable2: "value2",
}
let replaced = str.replace(/{#(.*?)#}/g, (m, p1) => map[p1])
console.log(replaced)
Regex demo
This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 5 years ago.
I am having problem finding the proper method to accomplish this in JS. I want to iterate through each character of string (assume all lower cased) while removing ith character only.
So if I have string abc, I will iterate it three times and it will print:
'bc' //0th element is removed
'ac' //1st element is removed
'ab' //2nd element is removed
I thought I could do it with replace, but it did not work on string having multiple same characters.
Something like this:
str = 'batman';
for(var i = 0; i < str.length; i++){
var minusOneStr = str.replace(str[i], '');
console.log(minusOneStr);
}
"atman"
"btman"
"baman"
"batan"
"btman" //need it to be batmn
"batma"
I realized this didn't work because str.replace(str[i], ''); when str[i] is a, it will replace the first instance of a. It will never replace the second a in batman. I checked on substring, splice, slice method, but none suits mf purpose.
How can I accomplish this?
Instead of using .replace() you'd just concatenate slices of the string before and after the current index.
var str = 'batman';
for (var i = 0; i < str.length; i++) {
var minusOneStr = str.slice(0, i) + str.slice(i + 1);
console.log(minusOneStr);
}
This is because, as you noted, .replace(), when given a string, always replace the first instance found.
This question already has answers here:
detect differences between two strings with Javascript
(2 answers)
Closed 8 years ago.
I am wondering if there is a way in JavaScript by which I can detect which part of my Strings makes them different from each other.
Let's say I have three strings as follows:
String1 = "Java1String"
String2 = "Java2String"
String3 = "Java3String"
If I choose my first String as a main one, the part which makes it different from the others is 1.
Is there any way using either JavaScript or jQuery by which I can find this part?
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out a demo of this code with this jsfiddle.
You can compare two strings like this. This will give you the characters which are different.
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out Demo of this code on this link
http://jsfiddle.net/enL9b3jv/1/
The naive solution would be to convert each string into an array and iterate over the arrays, compare the character at each index until you find an index that doesn't match, and then write that index to a variable. Below is a Jsbin that does just that, but just as DevIshOne states, there are many questions to answer here...
http://jsbin.com/dugovemoxupu/1/edit
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove a word from a string
I have a simple string var mystr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit", and I have an array var lipsums = new Array("dolor","consectetur","elit"); Now, I want a simple function which will remove any same word in the string.
So, in the above example, it should remove the words "dolor", "consectetur", and "elit" and my string mystr should be "Lorem ipsum sit amet, adipiscing"
This script should be in Javascript (no jQuery). Any help would be appreciated.
Loop over the array of words to remove, removing all occurances via split/join:
for (var i = 0; i < lipsums.length; i++) {
mystr = mystr.split(lipsums[i]).join('');
}
http://jsfiddle.net/9Rgzd/
You may also want to clean up your whitespace afterwards, which you can do with a regex:
// Note: don't do this in the loop!
mystr = mystr.replace(/\s{2,}/g, ' ');
http://jsfiddle.net/9Rgzd/1/
Like this:
for(i=0; i<lipsums.length; i++) {
mystr = mystr.replace(new RegExp(lipsums[i],"g"), "");
}
Add this AFTER the loop to remove double white space's:
mystr = mystr.replace(/\s{2,}/g, ' ');