I have this string where there are a bunch of usernames like this -
var someString = "#earth #moon";
And I want the string to be like this -
"[#earth](https://www.somewebsite.com/earth) [#moon](https://www.somewebsite.com/moon)"
I have thought of using regex expressions, but I am not really good in regex
console.log(myStr.replace(/[a-z0-9A-Z-_]/,
"[" + /[a-z0-9A-Z-_]/ +"](https://www.website.com/" + /[a-z0-9A-Z-_]/
);
How to do it?
Assuming you always have the same pattern separated by whitespace, you don't need much of a regex, just split on space and replace the #:
var someString = "#earth #moon";
var str = someString.split(/\s+/).map(item =>
`[${item}](https://www.somewebsite.com/${item.replace('#', '')})`)
.join(" ")
console.log(str)
Related
I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps
highlightStr: function (body, searchString){
console.log(searchString);
var regex = new RegExp('(' + searchString + ')', 'gi');
console.log(regex)
return body.replace(regex, "<span class='text-highlight'>$1</span>");
}
Above is the code I'm using. I want to find and replace the searchString, which could be anything. It works fine for most words, but fails when finding words with apostrophes.
How can I modify the regex to include special characters like the appostrophe.
var body = "<br>I like that Apple’s.<br>";
var searchString = "Apple's";
Thank you
You should escape the search string to make sure the regex works OK even if the search string contains special regex metacharacters.
Besides, there is no need wrapping the whole pattern with a capturing group, you may always reference the whole match with $& placeholder from the replacement pattern.
Here is an example code:
var s = "I like that Apple's color";
var searchString = "Apple's";
var regex = new RegExp(searchString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
document.body.innerHTML = s.replace(regex, '<b>$&</b>');
How can I remove all urls within a string regardless of where they appear using Javascript?
For example, for the following tweet-
"...Ready For It?" (#BloodPop ® Remix) out now - https://example.com/rsKdAQzd2q
I would like to get back
"...Ready For It?" (#BloodPop ® Remix) out now -
To remove all urls from the string, you can use regex to identify all the urls that are there in the string and then use String.prototype.replace to replace all the urls with empty characters.
This is John Grubber's Regex which can be used to match all urls.
/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g
So to replace all the urls just run a replace with the above regex
let originalString = '"...Ready For It?" (#BloodPop ® Remix) out now - https://example.com/rsKdAQzd2q'
let newString = originalString.replace(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/g,'')
console.log(newString)
If your urls do not contain a literal whitespace, you could use a regex https?.*?(?= |$) to match from http with an optional s to the next whitespace or end of the string:
var str = '...Ready For It?" (#BloodPop ® Remix) out now - https://example.com/rsKdAQzd2q';
str = str.replace(/https?.*?(?= |$)/g, "");
console.log(str);
Or split on a whitespace and check if the parts start with "http" and if so remove them.
var string = "...Ready For It?\" (#BloodPop ® Remix) out now - https://example.com/rsKdAQzd2q";
string = string.split(" ");
for (var i = 0; i < string.length; i++) {
if (string[i].substring(0, 4) === "http") {
string.splice(i, 1);
}
}
console.log(string.join(" "));
First you can split it by white space
var givenText = '...Ready For It?" https://example2.com/rsKdAQzd2q (#BloodPop ® Remix) out now - https://example.com/rsKdAQzd2q'
var allWords = givenText.split(' ');
Than you can filter out non url words using your own implementation for checking URL, here we can check index of :// for simplicity
var allNonUrls = allWords.filter(function(s){ return
s.indexOf('://')===-1 // you can call custom predicate here
});
So you non URL string will be:
var outputText = allNonUrls.join(' ');
// "...Ready For It?" (#BloodPop ® Remix) out now - "
You can use a regular expression replace on the string to do this, however, finding a good expression to match all URLs is awkward. However something like:
str = str.replace(regex, '');
The correct regex to use has been the subject of many StackOverflow questions, it depends on whether you need to match only http(s)://xxx.yyy.zzz or a more general pattern such as www.xxx.yyy.
See this question for regex patterns to use: What is the best regular expression to check if a string is a valid URL?
function removeUrl(input) {
let regex = /http[%\?#\[\]#!\$&'\(\)\*\+,;=:~_\.-:\/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789]*/;
let result = input.replace(regex, '');
return result;
}
let result = removeUrl('abc http://helloWorld" sdfsewr');
Using javascript (including jQuery), I’m trying to replace all but the last non-breaking space if multiple words are joined.
For example:
Replace A String of Words with A String of Words
I think you want something like this,
> "A String of Words".replace(/ (?=.*? )/g, " ")
'A String of Words'
The above regex would match all the strings except the last one.
Assuming your string is like this, you can use Negative Lookahead to do this.
var r = 'A String of Words'.replace(/ (?![^&]*$)/g, ' ');
//=> "A String of Words"
Alternative to regex, easier to understand:
var fn = function(input, sep) {
var parts = input.split(sep);
var last = parts.pop();
return parts.join(" ") + sep + last;
};
> fn("A String of Words", " ")
"A String of Words"
How to ignore newline in regexp in Javascript ?
for example:
data = "\
<test>11\n
1</test>\n\
#EXTM3U\n\
"
var reg = new RegExp( "\<" + "test" + "\>(.*?)\<\/" + "test" + "\>" )
var match = data.match(reg)
console.log(match[1])
result: undefined
In JavaScript, there is no flag to tell to RegExp() that . should match newlines. So, you need to use a workaround e.g. [\s\S].
Your RegExp would then look like this:
var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );
You are missing a JS newline character \ at the end of line 2.
Also, change regexp to:
var data = "\
<test>11\n\
1</test>\n\
#EXTM3U\n\
";
var reg = new RegExp(/<test>(.|\s)*<\/test>/);
var match = data.match(reg);
console.log(match[0]);
http://jsfiddle.net/samliew/DPc2E/
By reading this one: How to use JavaScript regex over multiple lines?
I came with that, which works:
var data = "<test>11\n1</test>\n#EXTM3U\n";
reg = /<test>([\s\S]*?)<\/test>/;
var match = data.match(reg);
console.log(match[1]);
Here is a fiddle: http://jsfiddle.net/Rpkj2/
Better you can use [\s\S] instead of . for multiline matching.
It is the most common JavaScript idiom for matching everything including newlines. It's easier on the eyes and much more efficient than an alternation-based approach like (.|\n).
EDIT: Got it:
I tried to use this regex in notepad++ But the problem is that it finds the whole text from beginning to end
MyRegex:
<hostname-validation>(.|\s)*<\/pathname-validation> (finds everything)
/<hostname-validation>(.|\s)*<\/pathname-validation>/ (finds nothing)
/\<hostname-validation\>([\s\S]*?)\<\/pathname-validation\>/ (finds nothing)
**<hostname-validation>([\s\S]*?)<\/pathname-validation> (my desired result)**
The text where I use in:
<hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="false"/>
<validate-absence type="boolean">false</validate-absence> (...) <hostname-validation>www.your-tag-name.com</hostname-validation>
<pathname-validation>pathname</pathname-validation> <response-validation nil="true"/>
<validate-absence type="boolean">false</validate-absence> (...)