String replace logic - javascript

I'm trying to build a function, that receives a string with this format:
"hello wor**"
The * could be anywhere on the string.
It should return:
<span>hello wor</span><input type='text'></input>
So the string could be "hel** wor*d" also
and the return should be:
<span>hel</span><input type='text'> <span>wor</span><input type='text'><span>d</span>
I could do it easily with a loop on each char, but I'm looking for more elegant solutions.
I think that it could be solved with a regex, and using replace I got the "*" covered:
var text = "hello wor**";
text.replace(/\*+/g, "<input type='text'></input>");
I have not yet found a way of capturing the remaining text to render the
<span>

You're not using the result of the replace function. Try this:
var text = "*hel** wor*d*";
var element = text.split(/\s*\*+\s*/g);
element = "<span>"+ element.join("</span><input type='text'><span>") + "</span>";
element = element.replace(/<span><\/span>/g, "");
console.log(element);

'hello wor**'.replace(/\*+/g, "<input type='text'></input>");
This returns hello wor. All you have to do is concatenate the string with the rest of the data you want, like so:
var text = "hello wor**";
text = '<span>' + text.replace(/\*+/g, '') + '</span><input type=\'text\'></input>';

<html>
<head>
</head>
<body>
<span id="hi">hello wor**</span>
</body>
</html>
i use jquery in this
$( document ).ready(function() {
var texty = $('#hi').text();
$('#hi').replaceWith(texty.replace(/\*+/g, "<input type='text'></input>"))
});

Related

extract text values from a string like html

I have this string (not html but string):
<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>
Need to extract text value of rTag so result should be a new string:
ATINA,BELMOPAN,DAMASK,FILIPINI,BANGKOK
Any help?
This will set the content of #output to the new str, but you can do whatever you want after its joined.
var str = [];
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var $html = $($.parseHTML("<div>" + content + "</div>"));
$html.find(".rTag").each(function(){
str.push($(this).html());
});
$("#output").html(str.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="output"></div>
Parsing an HTML string into a DOM element so that it can be processed by javascript/jquery is a fairly standard process:
$(content)
will suffice without needing to add it to the DOM (and all that entails behind the scenes).
In this case:
var content = '<div class="rTag">ATINA</div><div class="rTag">BELMOPAN</div><div class="rTag">DAMASK</div><div class="rTag">FILIPINI</div><div class="rTag">BANGKOK</div>';
var arr = $(content).filter(".rTag").map(function() {
return $(this).text();
}).get();
console.log(arr.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Using javascript/jquery to remove text after a certain character

Is there a way to replace/remove the text only after a certain character using jQuery or Javascript? I want to remove text after the dot '.' from an element.
You can easily do it with .split() like this:
var text = 'daslkdaskldj.asdasdasd';
text.split('.')[0];
here is fiddle
var string = "Test String.Test String 2".split('.')[0];
console.log(string)
Will give you the output:
Test String
Here is a working example:
https://jsfiddle.net/zr2wg90d/
Your question is a bit unclear. But to remove all text after the first '.'(dot) This can do the trick with an input field. There are a lot of ways to achieve this. This is a solution without jQuery.
function removeAfterDot() {
var test = document.getElementById("myInput").value;
alert("String before remove: " + test);
test = test.substr(0, test.indexOf('.'));
alert("String after remove: " + test);
}
<input type="text" id="myInput" onchange=removeAfterDot();>
text.substr(0, text.indexOf('.'));
Hope this helps.
var q = 'https://stackoverflow.com/questions/';
q = q.substring(0, q.indexOf('.'));
alert(q);
Try this
var yourString = "Hello. World";
yourString.substr(0, yourString.indexOf('.'));
Will give you the following output
Hello
you can use this. split any string at the character you give it.
<p>first part . second part</p>
remove
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('a').click(function(){
var the_string = $('p').text();
var removed = the_string.split('.', 1);
$('p').text(removed);
});
</script>
for me splice works, I basically use this for removing characters after a hyphen or a comma etc.
var text = 'Tellme.more';
text.split('.')[0]);
//Consoles out -> Tellme

Unable to span wrap html text with single or double quotes

Contenteditable div
var1 = 'x';
var2 = someVar
Target
<span class="frag">var1 = 'x'</span>;
<span class="frag">var2 = someVar</span>;
JS
$('#board_code_dup').children().each(function (index, child) {
var text = $(child).html();
//HOW TO DO THIS RIGHT?
text = text.replace(/([A-Za-z0-9_]+\s*=\s*[A-Za-z0-9&'"]+)/g, '<span class="frag">$1</span>');
});
How would i use HTML entities " &apos; here instead of ' " so that i can properly wrap it?
This is what I've tried "$('#board_code_dup').text()" and split it on "\n" instead ..
It will convert entities behind the scene like quotes or double quotes in the source. This might match in reg-exp.
var result = $('#board_code_dup').text().split("\n").map(function (el, idx){
return el.replace(/\s*;\s*$/,'').replace( /(\w+\s*=\s*[\w&"']+)/g,'<span class="frag">$1</span>');
});
alert(result.join(''));
Js fiddle Here
I hope this will help ..

return the text value of tags and append a line break to each tag

So if I call this function:
$("#item").text()
on this HTML code:
<div id="item">
<pre><span class="cm-tag"><html></span></pre><pre><span class="cm-tab"> </span>asdf</pre><pre><span class="cm-tag"></html></span></pre>
</div>
it returns:
'<html> asdf</html>'
and i want it to return:
'<html>
asdf
</html>'
basically i need a new line after each <pre> tag... how would i do this?
A possible solution, get the text of each pre and join them with new lines:
var text = $("#item pre").map(function(){
return $(this).text();
}).get().join('\n');
Here is the jsfiddle: http://jsfiddle.net/uGGFe/
Another option for you:
var clone = $("#item").clone(); //create a clone we can manipulate
clone.find('pre').after('\n'); //stick new lines in after <pre> tags
alert(clone.text()); //behold the alert glory
http://jsfiddle.net/SrV9c/1/
var text = '';
$("#item pre").map(function(i, el) {
return $(el).text().replace(/\s/g, '')
}).each(function(i, val) {
if (i == 0)
text += val.concat('\n\t');
else
text += val.concat('\n');
});
​
Working sample
because jQuery search match htmlElement use regular expression, when regular expression match content first delete "\r\n", so you see the content not have "\r\n"

How to show a string on a page

This is a really stupid question.
I have a javascript string variable for a name, and i want to display it where it says user like this:
"Hello, user!" --> "Hello, Chris!
Surely you could have found this answer out easily yourself :p
Put the name in a span and give it an ID
Hello <span id="name"></span>
Then set the text using getElementByID
var name = "Chris";
document.getElementById('name').innerHTML = name;
var user_name = 'Chris';
document.writeln("Hello, " + user_name);
I think document.write plus some string concatenation are what you're looking for:
var user = "Chris";
document.write("Hello, " + user + "!");
Something like this will do the trick.
var user = 'Steve';
document.write('hello ' + user);
If you need to target an element, you can use the usual methods, such as:
var user = 'Steve';
var thisOne = document.getElementById('thisOne');
thisOne.innerHTML = ('hello ' + user);
May as well throw in a jsfiddle so you can play around an experiment.
This is example of dislay string into span tag.
'+' operator uses for string concatenation.
<html>
<head>
<script>
var name = 'Chris';
var field = document.getElementById('show_string');
field.innerHTML( '"Hello, '+ name + '!"' );
</script>
</head>
<body>
<span id='show_string'></span>
</body>
</html>
You can concatenate the user's name with the rest of the string you want to display like so:
<p id="hello"></p>
<script type='text/javascript'>
var user_name = "Chris";
var hello_string = "Hello, " + user_name;
document.getElementById("hello").innerHTML = hello_string;
</script>

Categories