Remove text to the right of a character in JS - javascript

I am using JS to remove/replace characters from a Page Title to show the slug/url as
function convertToSlug(Text){
return Text
.toString()
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
This will convert a page title of This is a page title | Company Name to this-is-a-page-title-company-name but how can I remove all text to the right of the | so that the returned slug is this-is-a-page-title?
Please note that the company name will change and just removing the whole part of | Company Name isn't sufficient. I need it to apply to any version of the title to the right of |.

Replace the pipe symbol (|), and everything after it with an empty string:
function convertToSlug(Text){
return Text
.replace(/\|.*/, '')
.trim()
.toLowerCase()
.replace(/\s+/g, '-');
}
console.log(convertToSlug('This is a page title | Company Name'));

assuming that you are using | char as seperator, you can use following:
function convertToSlug(Text){
return Text
.split('|')[0]
.trim()
.toLowerCase()
.replace(/\s/g,"-");
}

Late reply, but could be useful to someone else.
<input type="text" id="txtInput" />
<input type="button" onclick="return convertToSlug();" value="Remove text to the right of a character in JS
">
<script>
function convertToSlug(){
var Text = document.getElementById("txtInput");
var purgeCharPosition = Text.indexOf("|");
return Text
.toString()
.trim()
.substr(purgeCharPosition)
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
</script>

Related

Add "#" before every word + ONE space between every word (JavaScript)?

I put together a code, in the input field one writes words and the output shows same words but with # attached and have one space in between each words. The code I have so far is semi-functional, it kinda does what I want to do, but with some issues.
I need some help with a few things:
1. I need to make sure that the ouput always has one space in between characters.
If a user inputs (types or pastes) a sentence with MORE THAN ONE "space", the output shrinks it down to one space.
As you can see:
Currently if you input: tomato, orange, (double space) apple, it will output #tomato #orange # #apple.
I want it to the output be: #tomato #orange #apple (remove the extra #, that was inserted due to double space)
2. When one deletes everything typed in the input field, the output still shows "#". I want the output be blank just like input if one deletes the input field.
Here is the code:
function atPrefix (text) {
return text
.split(' ')
.map(character => '#' + character)
.join(' ')
}
<textarea id="specialInput" type="text" oninput="document.querySelector('#output').innerText = atPrefix(this.value)"></textarea>
<p> <textarea
id="output">
</textarea>
</p>
Add a filter() function to filter out any token that is only made of spaces:
function atPrefix (text) {
return text
.split(' ')
.filter(token => token.trim() !== '')
.map(token => '#' + token)
.join(' ')
}
<textarea id="specialInput" type="text" oninput="document.querySelector('#output').innerText = atPrefix(this.value)"></textarea>
<p> <textarea
id="output">
</textarea>
</p>
Something like this should work
function atPrefix (text) {
if(text) {
return text
.replace(/\s\s+/g, ' ')
.split(' ')
.map(character => '#' + character)
.join(' ')
} else { return text }
}
So basically you are checking if text is not an empty string, and replacing multiple space characters with single space through regex.
your code is good but after the split just use then array.filter(e=>!!e);
function atPrefix (text) {
return text.split(' ')
.filter(word => !!word)
.map(word => '#' + word.trim())
.join(' ')
}
<textarea id="specialInput" type="text" oninput="document.querySelector('#output').innerText = atPrefix(this.value)"></textarea>
<p> <textarea
id="output">
</textarea>
</p>
You can find an explanation for this regex here: https://regexr.com/4qgs7
function atPrefix (text) {
return text.replace(/\b(\w+)\b/gm,"#$1");
}
<textarea id="specialInput" type="text" oninput="document.querySelector('#output').innerText = atPrefix(this.value)"></textarea>
<p> <textarea
id="output">
</textarea>
</p>
using regular express to replace ",?\s+" with " #" and prefix with leading #;
Do the string manipulation only when it's not blank. this will address your second problem.

How can i remove all characters started with # from a textarea using jquery or javascript?

I have the code below
<textarea id="description" name="description" rows="10" placeholder="Description..." class="valid">
This is an example text i wanna keep.
# And i want to remove all this content.
</textarea>
how can i remove only this text from the textarea
# And i want to remove all this content.
using jquery or javascript ?
As you can see i want all the content that start with a hashtag to be removed.
Only for textarea, you may use a simple Regular Expression, with "m" (multiline) flag.
• Where $ means end of the line;
• special . matches with any symbol,
• * means 'match from zero to infinite times'
let desc = document.getElementById('description');
desc.value = desc.value.replace(/#.*$/gm,"");
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description...">
This is an example text i wanna keep.
# And i want to remove all this content.
Bubu and replace #Me
But not me!
</textarea>
Version for multiple elements, textarea, div, etc - replace by className:
let replace = document.querySelectorAll('.js-replace')
for( let i = 0; i < replace.length; i++ ){
let area = /TEXTAREA|INPUT/.test(replace[i].tagName); // will return true or false;
let content = area ? "value" : "innerHTML";
// Ternary operator. (condition) ? (value if true) : (value otherwise)
// replace[i]['value'] if textarea and replace[i]['innerHTML'] if other element
replace[i][content] = replace[i][content].replace(/#.*?(\n|<br>|$)/g, "$1"); // (*1)
}
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description...">
This is an example text i wanna keep.
# And i want to remove all this content.
Bubu and replace #Me
But not me!
</textarea>
<div class="js-replace">
This is an example text i wanna keep.
<br># And i want to remove all this content.
<br>
<br>Bubu and replace #Me
<br>But not me!
</div>
(*1): .replace(/#.*?(\n|<br>)/g, "$1") — string, starting from # symbol, matching .* anything (instead of line-break \n), many times, and ? stop as soon as it faces with \n line break | or <br> HTML-line break. "$1" — equals to match in the first (parentheses). I.e. we replace all string, but keep line-break.
But this will not work correctly, if you want to delete, for example, comments from Python... because you may delete strings with "str... # str"

How to replace \n with <br> in JSON string?

I'm getting the following raw string from a JSON file. I console.log it display fine.
"Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back "
When I rendering this string, there is no new lines.
the best way in my case is just add in css : white-space: pre-wrap;
If you insert that string into HTML, it will render by literally showing the \n and \r elements:
const string = 'Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back';
document.write(string);
You need to replace them with HTML <br> elements:
const string = 'Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back';
const renderString = string.replace(/(?:\r\n|\r|\n)/g, "<br>");
document.write(renderString);
Regex above from this answer.
I think this problem occurs when you use innerHTML, use <br/> instead of /r/n.
Example:
"Hello, my name is Jane, from 'IStaff' company.<br/> <br/> .We are interested in your service.<br/> <br/> .Please call me back "
"Hello, my name is Jane, from 'IStaff' company. .We are interested in your service. .Please call me back "
Whitespace characters like newlines do not render in HTML. You have to change the \n into <br>
function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
dataReceveid = function(json) {
$("div").html(nl2br(json.str));
}
$(function() {
dataReceveid({
str: '"Hello, my name is Jane, from "IStaff" company.\r\n\r\n.We are interested in your service.\r\n\r\n.Please call me back "'
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
The browser doesn't know what does it means \r\n. The language the web browser know only is HTML and \r\n is not an HTML language word. To break the line in the browser you have to use HTML language tag <br /> so the browser can consider it and break the lines.
So the simple solution to your problem is replacing \r\n with <br /> HTML tag/element.

JavaScript Replace - Convert br Tags To New Lines

I have a JavaScript function that looks like this:
function onAfterTranslate(item, translator) {
var thing = item.translated_text;
document.myform.keywords.value = "Translated Text:\r\n\r\n" + thing.replace(/<br>/g, "\r\n");
}
The parameter named item is an object, which includes an property called translated_text.
These are the contents of this variable:
mono <br> toro <br> gato <br> perro <br> elefante
What I want to do is convert the br tags to newline characters. (Ideally, it should look for optional spaces immediately before and after the br tag, and it should also accept any of the valid formats of br tag that exist, but that's not crucial at the moment.)
However, the replace command in the above code is not working, and I can't work out why.
If I remove the replace command so the line ends with the variable name thing, then it behaves as expected, updating the textarea box in my form with the correct value.
Even if I try replacing the letter "o" with an asterisk, it still doesn't work, which would suggest I'm doing something fundamentally wrong here.
Any suggestions?
You can use \s to look for spaces and ? for "preceding char may occur once or not". The regex is here below.
/\s?(<br\s?\/?>)\s?/g
Here below is an example with all possible br tags: <br>, <br /> and <br/> with some spaces in between.
var input = document.getElementById('input').value;
console.log(input);
document.getElementById('output').value = input.replace(/\s?(<br\s?\/?>)\s?/g, "\r\n");
textarea {
width: 400px;
height: 100px;
}
<h3>input</h3>
<textarea id="input">
fooo <br> bar <br> lorum ipsum dolor.
valar durum <br /> kel alar fol <br /> durom <br />.
a bread of kebab is tasteful !<br/>
EOL
</textarea>
<hr />
<h3>output</h3>
<textarea id="output"></textarea>
try
var text = "mono <br> totono <br> gato <br> elefante"
console.log( text.split( "<br>" ).join( "\n" ) );
and for trimming white spaces
text.split( "<br>" ).map( function(val){ return String(val).trim(); } ).join( "\n" );
for putting this in a textarea
document.body.innerHTML += "<textarea>" + text.split( "<br>" ).map( function(val){ return val.trim() } ).join( "\n" ) + "</textarea>" ;
So, it turns out the replace function was essentially fine (but enhanced now thanks to your contributions) - it was the format of the input data that was not what I was expecting.
I thought that the variable item.translated_text was an array element (because when I echoed it to the screen, I saw the value I was expecting), but it turned out it was actually an array, as I found out when I displayed the length of the variable and found it was only 1.
I now suspect that the item variable was a JSON construct and not a regular array, as I first thought.
Sorry if I wasted anyone's time on this.

How can I filter matches inside a specific tag?

I'm trying to replace all ocurrences of a text in an input field which enhanced with TinyMCE, this has to occur every time the user presses the spacebar (similar to the autocorrect feature in Word).
The problem I have is when the replaced string contains the trigger, it keeps replacing it again and again.
For example replacing "hello" with
<span class="replaced">hello world</span>
It will replace it again as
<span class="replaced"><span class="replaced">hello world</span> world</span>
So I have to write a regexp to filter out matches in text that has already been replaced.
Can you help me out?
This is my current code:
for (r in autocorrect_replacements) {
if (newHtml.indexOf(autocorrect_replacements[r][0]) > -1) {
replacement_html = '<span class="replaced">'+autocorrect_replacements[r][1] + '</span>';
newHtml = newHtml.replace(autocorrect_replacements[r][0],replacement_html);
ed.setContent(newHtml);
}
I'm not a fan of regular expressions, but I think it's the correct solution in this case.
The regex to get the span would be /<span class="replaced">.*<\/span>/. Not sure if its the right solution.
You can do something like this:
for (r in autocorrect_replacements) {
if (newHtml.indexOf(autocorrect_replacements[r][0]) > -1) {
if (!(/<span class="replaced">.*<\/span>/.test(autocorrect_replacements[r][1]))){
replacement_html = '<span class="replaced">'+autocorrect_replacements[r][1] + '</span>';
newHtml = newHtml.replace(autocorrect_replacements[r][0],replacement_html);
ed.setContent(newHtml);
}
}

Categories

Resources