JavaScript find and replace a character in between specified characters - javascript

I'm trying to replace all [space] with - between __tt and tt__
I could replace space in the entire string with below regex.
var str = document.getElementById('tt').value;
str = str.replace(/(?<=__tt.*) (?=.*tt__)/g, '-');
console.log(str);
textarea {
width: 400px;
min-height: 100px;
}
<textarea id="tt">This is a long text __tt where i want
to replace
some text tt__ between some character
</textarea>
Is there a way I could do the replace only between __tt and tt__ tag ???

You could take positive look behind and look ahead.
var str = 'This is a long text __tt where i want to replace some text tt__ between some character';
str = str.replace(/(?<=__tt.*) (?=.*tt__)/g, '-');
console.log(str);

Without lookarounds, which are not yet fully supported by all browsers you might also use a replacement using a callback function over the selected match only.
str = str.replace(/__tt.*?tt__/g, m => m.replace(/ /g, "-"));
var str = 'This is a long text __tt where i want to replace some text tt__ between some character';
str = str.replace(/__tt.*?tt__/g, m => m.replace(/ /g, "-"));
console.log(str);
Note
If you want a single hyphen in the replacement for multiple consecutive spaces, you could repeat the space 1 or more times using + or match 1 or more whitespace chars using \s+
With the updated question, get the text of the element:
var elm = document.getElementById("tt");
elm.textContent = elm.textContent.replace(/__tt[^]*?tt__/g, m => m.replace(/ +/g, "-"));
<textarea id="tt" rows="4" cols="50">This is a long text __tt where i want
to replace
some text tt__ between some character
</textarea>

can try it
let str = 'This is a long text __tt where i want to replace some text tt__ between some character';
str = str.replace(/__tt.*?tt__/g, (item) => item.replace(/ /g, "-"));
console.log(str);

Related

Highlighting lines that contain a phrase using regex

I'm highlighting lines that contain a certain phrase using regex.
My current highlight function will read the whole text and place every instance of the phrase within a highlight span.
const START = "<span name='highlight' style='background-color: yellow;'>";
const END = "</span>"
function highlight(text, toReplace) {
let reg = new RegExp(toReplace, 'ig');
return text.replace(reg, START + toReplace + END);
}
I want to expand my regex so that, for each phrase, it highlights from the preceding <br> to the following <br>.
highlight("This<br>is some text to<br>highlight.", "text");
Current output:
This<br>is some<span name="highlight" style="background-color:yellow;">text</span> to<br>highlight."
Wanted output:
This<br><span name="highlight" style="background-color:yellow;">is some text to</span><br>highlight.
You may want to match all chars other than < and > before and after the text and it is advisable to escape the literal text you pass to the RegExp constructor. Also, to replace with the whole match, just use $& placeholder:
const START = "<span name='highlight' style='background-color: yellow;'>";
const END = "</span>"
function highlight(text, toReplace) {
let reg = new RegExp("(<br/?>)|[^<>]*" + toReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "[^<>]*", 'ig');
return text.replace(reg, function ($0,$1) { return $1 ? $1 : START + $0 + END; });
}
console.log(highlight("This<br>is some text to<br>highlight.", "text"));
console.log(highlight("This<br>is a bunch of<br>text", "b"));
The regex will look like /[^<>]*text[^<>]*/gi, it will match 0 or more chars other than < and >, then text in a case insensitive way and then again 0 or more chars other than < and >, and the $& in the replacement will put the matched value into the highlighting tags.
My guess is that this simple expression,
(<br>)(.*?)(\1)
might work here.
const regex = /(<br>)(.*?)(\1)/gs;
const str = `This<br>is some text to<br>highlight. This<br>is some text to<br>highlight. This<br>is some text to<br>highlight.
This<br>is some
text to<br>highlight. This<br>is some text to<br>highlight. This<br>is some text to<br>highlight.`;
const subst = `$1<span name='highlight' style='background-color: yellow;'>$2</span>$3`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
In this demo, the expression is explained, if you might be interested.

Replace # and \s from a string using JavaScript

I am trying to replace # and space from a string if it has these two characters.
This is for markdown previewer.
var t = document.getElementById("textbox");
var h1 = (t.value === "/#\s/") ? t.value.replace(/^[#\s]/, "") : t.value;
console.log(h1);
How do I solve this problem?
If you want to categorically strip all pounds signs and spaces, then you should be using:
//var t = document.getElementById("textbox");
var t = "Hello#World Goodbye";
t = t.replace(/[# ]/g, "");
console.log(t);
Note the character for space, is just space, not \s, which means all whitespace (including things like newlines and tabs).
Try
let h1 = textbox.value.replace(/#| /g, '');
console.log(h1);
<input id="textbox" value="H a v e Nice#Day###">

Replace string after 3 different strings and between double quotes

I need your help again with a regex.
I have this string:
some string
text1
name="yyy", path="C:/asdf/qwer.jpg" type="jjj"
text2
name="3yu", path="C:/asdf/12t2.mov" type="uuu"
And I have this regex by far:
/\b(string\b(.|\n)*?)\btext1\b/
Now, I need to replace the path of text1 so the output will be:
some string
text1
name="yyy", path="D:/here/is/my/another/path.png" type="jjj"
text2
name="3yu", path="C:/asdf/12t2.mov" type="uuu"
I know that I need to use this also (lmk if I wrong, also what is better to use?):
/".*?"/
or:
/"[^"]*"/
But how do I tell it to replace like I need?
You can replace that string this way:
var re = /(string[\s\S]*?text1[\s\S]*?\bpath=")[^"]+/;
var str = 'some string\n\ntext1\n\nname="yyy", path="C:/asdf/qwer.jpg" type="jjj"\n\ntext2\n\nname="3yu", path="C:/asdf/12t2.mov" type="uuu"';
var subst = '$1D:/here/is/my/another/path.png';
document.write(str.replace(re, subst).replace(/\n/g,"<br/>"));
The regex is
/(string[\s\S]*?text1[\s\S]*?\bpath=")[^"]+/
EXPLANATION:
(string[\s\S]*?text1[\s\S]*?\bpath=") - a capturing group that will capture the text into group 1 that we'll refer to later usign a $1 backreference in the replacement string. It matches:
string - literal string
[\s\S]*? - any 0 or more characters, as few as possible
text1 - text1 literally
[\s\S]*? - any 0 or more characters, as few as possible
\bpath=" - matches path=" literally with a non-word character (e.g. space) before path (you may remove it if it is part of a longer word)
[^"]+ - 1 or more characters other than ".
(\bstring\b[\s\S]*?\btext1\b(?:(?!\btext\d+\b)[\s\S])*path=")[^"]*
You can use this.Replace by $1mypath.See demo.
https://regex101.com/r/fX3oF6/3
var re = /(\bstring\b[\s\S]*?\btext1\b(?:(?!\btext\d+\b)[\s\S])*path=")[^"]*/g;
var str = 'some string\n\n text1\n\n name="yyy", path="C:/asdf/qwer.jpg" type="jjj"\n\n text2\n\n name="3yu", path="C:/asdf/12t2.mov" type="uuu"\n';
var subst = ' $1mypath';
var result = str.replace(re, subst);

Using js regex to replace simple markup styles like **bold** to <b>bold</b>

I'm trying to take a chunk of plain text and convert parts of it into html tags. I don't need a full rich editor, just these few tags:
**bold**
__underline__
~~italics~~
--strike--
<<http://www.link.com>>
This is the method I have attempted to write but my lack of regex/js seems to be holding it back:
function toMarkup($this) {
var text = $this.text();
text = text.replace("\*\*(.*)\*\*", "<b>$1</b>");
text = text.replace("__(.*)__", "<u>$1</u>");
text = text.replace("~~(.*)~~", "<i>$1</i>");
text = text.replace("--(.*)--", "<del>$1</del>");
text = text.replace("<<(.*)>>", "<a href='$1'>Link</a>");
$this.html(text);
}
Any glaring errors as to why these replaces are not working? Another issue I'm just now realizing is by converting this text to html I am unescaping any other potential tags that may be malicious. A bonus would be any advice on how to only escape these elements and nothing else.
First of all, they are just string, not regexs. Secondly you should use not-greedy .*.
Also, you may want to use the g modifier to match every occourrence in the text.
function toMarkup($this) {
var text = $this.text();
text = text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
text = text.replace(/__(.*?)__/g, "<u>$1</u>");
text = text.replace(/~~(.*?)~~/g, "<i>$1</i>");
text = text.replace(/--(.*?)--/g, "<del>$1</del>");
text = text.replace(/<<(.*?)>>/g, "<a href='$1'>Link</a>");
$this.html(text);
}
Use a Regexp object as the first argument to text.replace() instead of a string:
function toMarkup($this) {
var text = $this.text();
text = text.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
text = text.replace(/__(.*?)__/g, "<u>$1</u>");
text = text.replace(/~~(.*?)~~/g, "<i>$1</i>");
text = text.replace(/--(.*?)--/g, "<del>$1</del>");
text = text.replace(/<<(.*?)>>/g, "<a href='$1'>Link</a>");
$this.html(text);
}
Note that I also replaced all of the .* with .*? which will match as few characters as possible, otherwise your matches may be too long. For example you would match from the first ** to the very last ** instead of stopping at the next one. The regex also needs the g flag so that all matches will be replaced (thanks Aaron).
function toMarkup($this) {
$this.html ($this.text ().replace (/(__|~~|--|\*\*)(.*?)\1|<<(.*?)>>\/g,
function (m, m1, m2, m3) {
m[1] = {'**' : 'b>', '__': 'u>', '--': 'del>', '~~': 'i>'}[m[1]];
return m[3] ? 'Link'
: ('<' + m[1] + m[2] + '</' + m[1]);
});
}
Note that you cannot nest these, i.e. if you say __--abc--__ will be converted to <u>--abc--</u>.

Remove ALL white spaces from text

$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.
I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s instead:
.replace(/\s/g,'')
You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
Now you can use "replaceAll":
console.log(' a b c d e f g '.replaceAll(' ',''));
will print:
abcdefg
But not working in every possible browser:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
** 100% working
use replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_you
Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefg
I don't understand why we need to use regex here when we can simply use replaceAll
let result = string.replaceAll(' ', '')
result will store string without spaces
let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse
Use string.replace(/\s/g,'')
This will solve the problem.
Happy Coding !!!
simple solution could be : just replace white space ask key value
val = val.replace(' ', '')
Use replace(/\s+/g,''),
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.
let str = "D S# D2m4a r k 23";
// We are only allowed the character in that range A-Za-z
str = str.replace(/[^A-Za-z]/g,""); // output:- DSDmark
console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow
Using .replace(/\s+/g,'') works fine;
Example:
this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
let str = new String(ToRemove);
while(str.includes(" "))
{
str = str.replace(" ", "");
}
return str;
}

Categories