I am trying to replace the string below with whitespaces using javascript
function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g, " ");
}
I received the result as ABC EFG but I expect the result to come with two whitespace.
I also tried the same thing using php str.replace but still get the same result.
Is there any other methods i can used to replace the individual asterisk with whitespace??
P/S: The return string will be used as part of the sql query
[UPDATE]
I ended up return the string without any replacement to sql, then I use sql replace function to perform replacement in the query.
If you're displaying the resulting string in an HTML element then two or more whitespaces will be displayed as only one whitespace. To workaround this fact, use instead:
return str.replace(/\*/g, ' ');
try this
return str.replace(/\*/g, ' ');
Buddy the problem is with the HTML compiler which has its own special rules of parsing
So it parses multiple spaces into one.This can work for HTML only.
Thats why use the GIFT tag .
<pre>
<p id="para"></p>
</pre>
<script> function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g," ");
}
document.getElementById("para").innerHTML=replaceString();
</script>
<script>
function replaceString()
{ var str1=String.fromCharCode(32,32);
var str = "ABC**EFG";
return str.replace(/\*/g,str1);
}
alert(replaceString());
</script>
return of function from above code can be used directly in mysql...
Finally found the best solution, I replace those special characters using percent-encoding (URL-encoding)
for my case: str.replace(/\*/g, "%20");
Related
Trying for 2 hours to replace \r\n with < br/> but it seems to be impossible.
I don't know what i'm doing! Please help!
const text = '"Hello!\r\n\r\nThis is a dog!'
const checkText = str=> {
const match = /\r|\n/.exec(text);
if (match) {
//return str.replace(/(?:\\[rn]|[\r\n]+)+/g, '<br/>');
return str.replace('/r/n', '<br/>');
}
return str;
};
checkText(text)
Just do this:
text.replace(/\r\n/g, '<br/>');
Covering all the possible new line character combinations.
String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>"); // Old MAC
return tmp.replaceAll("\n", "<br>"); // Linux / UNIX
You may try:
(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
There are multiple things wrong with your code:
String.prototype.replace only replaces the first occurrence of a string. You need to use a regex argument with the /g flag to replace all occurrences.
Escapes use a backslash, not a forward slash: Use \r\n, not /r/n.
checkText returns a string, but your call-site doesn't do anything with the returned string - it's just dropped. Strings are immutable in JavaScript.
I don't recommend using strings to hold HTML because it can (very easily) cause HTML-injection (including <script>-injection) attacks.
Instead, do one of the following:
Use String.prototype.split and HTML-encode each string in the array and join with "<br />".
Add the string directly to the document with .textContent (don't use innerText anymore) and give the parent element the CSS style whitespace: pre-wrap;.
How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?
Example:
A variable passed from PHP as below:
"This is man.
Man like dog.
Man like to drink.
Man is the king."
I would like my result to look something like this after the JavaScript converts it:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
This will turn all returns into HTML
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
In case you wonder what ?: means.
It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later.
You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169
https://stackoverflow.com/a/36524555/5042169
If your concern is just displaying linebreaks, you could do this with CSS.
<div style="white-space: pre-line">Some test
with linebreaks</div>
Jsfiddle: https://jsfiddle.net/5bvtL6do/2/
Note: Pay attention to code formatting and indenting, since white-space: pre-line will display all newlines (except for the last newline after the text, see fiddle).
Without regex:
str = str.split("\n").join("<br />");
This works for input coming from a textarea
str.replace(new RegExp('\r?\n','g'), '<br />');
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
Shortest code supporting the most common EOL styles \r, \n, \r\n and using HTML5 <br>:
s.replace(/\r?\n|\r/g, '<br>')
Regardless of the system:
my_multiline_text.replace(/$/mg,'<br>');
It is also important to encode the rest of the text in order to protect from possible script injection attacks
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
This worked for me when value came from a TextBox:
string.replace(/\n|\r\n|\r/g, '<br/>');
For those of you who just want to allow max. 2 <br> in a row, you can use this:
let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');
First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br
Second line: Search for all single \r\n or \n and replace them with <br>
if you send the variable from PHP, you can obtain it with this before sending:
$string=nl2br($string);
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm
this will help you everytime.
Not answering the specific question, but I am sure this will help someone...
If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:
var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';
I had a config in PHP that was being passed in from the Controller. (Laravel)
Example: PHP Config
'TEXT_MESSAGE' => 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
Then in javascript using es6 reduce. notice I had to have two \\ or the output was not being replace correctly. Here are the parameters that are assoicated with the reduce function
previousValue (the value resulting from the previous call to
callbackfn)
currentValue (the value of the current element)
currentIndex Optional
array (the array to traverse) Optional
//p is previousVal
//c is currentVal
String.prototype.newLineReplace = function(){
return [...arguments].reduce((p,c) => p.replace(/\\n/g,c), this);
}
Here is how i used it in my script.
<script type="text/javascript">var config = #json($config);</script>
config.TEXT_MESSAGE.newLineReplace("<br />")
of course you could just called it on a javascript sring like...
let a = 'From:Us\nUser: Call (1800) 999-9999\nuserID: %s'
var newA = a.newLineReplace("<br />")
//output
'From:Us<br />User: Call (1800) 999-9999<br />userID: %s'
For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"
How would you go about finding a string constant that is not HTML-safe?
It appears the following searches for the individual characters.
var i = text.indexOf('»')
You'll first need to unescape the HTML in the pattern:
var i = text.indexOf(decodeHTML('»'));
function decodeHTML(s) { // e.g. using jQuery
return $('<div>' + s + '</div>').text();
}
var i = text.indexOf('\273')
would search for the actual character.
http://www.c-point.com/javascript_tutorial/special_characters.htm explains how to escape special characters in javascript.
Try looking at the html directly.
document.getElementById('search').innerHTML.indexOf('»')
Does JavaScript have a built-in function like PHP's addslashes (or addcslashes) function to add backslashes to characters that need escaping in a string?
For example, this:
This is a demo string with
'single-quotes' and "double-quotes".
...would become:
This is a demo string with
\'single-quotes\' and
\"double-quotes\".
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
A variation of the function provided by Paolo Bergantino that works directly on String:
String.prototype.addSlashes = function()
{
//no need to do (str+'') anymore because 'this' can only be a string
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
By adding the code above in your library you will be able to do:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
EDIT:
Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
Use encodeURI()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.
You can also use this
let str = "hello single ' double \" and slash \\ yippie";
let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));