remove parts of string with javascript - javascript

I have somewhat of an odd situation, where I need to fix a bug in a website where, when a string is created (dynamically) it adds 5 spaces before the string and 5 spaces after the string. Obviously, the best thing to do would be to fix the back end code and get rid of those spaces... long story short, I can't and I have to do it with javascript. I'm not quite sure how to do it, but this is what I was thinking
<!--Dynamically generated string including spaces added in backend-->
<span id="balance"> 245.34 </span>
My idea was to do the following with javascript
function removespace()
{
var oldString = document.getElementById('balance');
var newString = (THIS IS WHERE I AM STUCK... I NEED TO REMOVE THE SPACES);
document.getElementByID('balance').innerHTML = newString;
}
Does anyone have any suggestions?
Thanks!
ALSO FORGOT TO MENTION: I can't use any javascript libraries like prototype or jquery.
Edit: I have this so far... but it doesn't seem to be working:
<span id="balance"> $245.00 </span>
<script>
function removespace()
{
var oldString = document.getElementById('balance');
var newString = oldString.trim ();
document.getElementByID('balance').innerHTML = newString;
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
here is the solution I used... I finished it before I saw the other updates... but everyone was very helpful
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var oldString = document.getElementById('balance').innerHTML;
var newString = trim(oldString);
document.getElementById('balance').innerHTML = newString;

Unfortunetly JavaScript does not have a trim() function. But you can roll your own:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
and then do:
var newString = oldString.trim ();
the above function is from this website (first result on google for "javascript trim")
edit (based on your update to your question and comments):
change
var oldString = document.getElementById('balance');
to
var oldString = document.getElementById('balance').innerHTML;
and change
document.getElementByID('balance').innerHTML = newString;
to
document.getElementById('balance').innerHTML = newString; // notice the lower case d
and you have to call the removespace function at some point (but I'm sure you already do that) :)

Writting out of my head here.
var elem = doc.getElementById('balance');
var oldString = elem.innerHTML;
elem.innerHTML=oldString.(/^\s+|\s+$/g,"")
Something like that?
Edit: yep, only my first space is deleted, so I stole the whitespace from the answer number 1 :)

You try something like this
str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");

use trim() to remove all white spaces
var newString = oldString.trim();
or use replace to replace white spaces with empty string:
var newString = oldString.replace(" ","");

with jQuery it's simple:
var newStr = jQuery.trim(oldStr);

If balance is meant to be a double you could convert it to a string:
var c = '1234';
d = c * 1;
then back to a string if need be by:
d = c.toString();

Related

I want to use Regex so I can detect everything out of the ASCII code

So I'm trying to use some code that someone suggested, but I don't know how to make it work, so far I got this:
function Filter(){
var str = document.getElementById('TArea1').value;
var res = str.toString();
var regex = str.replace([^\x20-\x7E]+, "");
console.log(regex);
document.getElementById('TArea2').innerHTML = regex;
}
As far as I know
[^\x20-\x7E]+
says that everything out from the Hex code of ASCII characters from 20 to 7E (Which are the elements I want it to ignore) will be detected.
So far this exact code:
var regex = str.replace([^\x20-\x7E]+, "");
just crashes the components of the page where this is implemented.
So the code that fully answers my Question is below.
function Filter(){
var str = document.getElementById("TArea1").value;
var regex = new RegExp(/[^\x20-\x7E]+/,"g");
document.getElementById("TArea2").innerHTML = str;
var search = str.search(regex);
if(search>=0){
var bool = true;
} else {
var bool = false;
}
if(bool){
document.getElementById("TArea2").innerHTML = str.replace(str, "<span style='background-color:MediumSeaGreen';>"+str+"</span>");
}
Thank you everyone!.

reg expression created from variable not working in .replace()

I'm doing a coding challenge that wants us to create a function that finds and replaces a word in a sentence. I define the reg expression like this
//"before" is the parameter with the word to be replaced
var regRep = '/'+before+'/gi';
and I'm using it like this
//"str" is the sentence to search and prepAfter" is a variable with the replacement word.
var newStr = str.replace(regRep, prepAfter);
when returning newStr I get the original str without any modifications. I went through and console.log()ed each of my variables and chunks of logic and the replace() method is the only thing not working as it's suppose to. Here's the entire function.
function myReplace(str, before, after) {
var prepAfter = "";
var caseCheck = before.charAt(0);
var regRep = '/'+before+'/gi';
if(caseCheck === caseCheck.toUpperCase()){
var firstLetter = after.substr(0,1).toUpperCase();
var wordLength = after.length -1;
var remWord = after.substr(1,wordLength);
prepAfter = firstLetter.concat(remWord);
}
else{ prepAfter = after; }
var newStr = str.replace(regRep, prepAfter);
return newStr;
}
What am I missing?
var regRep = new RegExp(before, 'gi');
If you pass a string to replace() (as you did), it will look for the actual string.
Note: if before is just a word in your case, you might not even need a regex, just passing it to replace() as-is could do. Depends on whether or not you need to check things like whitespace before and after.

Removing special words from Delimitted string

Ive a situation to remove some words from a delimitted string in which the last char is ¶.
That means that if the string is:
keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6
The output string should be:
keyword1,keyword2,keyword4,keyword6
How can we achieve that in javascript?
This is what i did but i would like to do it without looping:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.split(',');
var t=[];
$(s).each(function(index,element){
var lastchar=element[element.length-1];
if(lastchar!='¶')
{
t.push(element);
}
});
console.info(t.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Problem can be solved using regular expressions:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.replace(/,keyword\d+¶/g, '');
console.info(s);
You should use the filter functionality in the JS.
var _s = "keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6";
var _output = _s.split(",").filter(function(word){
return (word[word.length - 1] !== "¶");
}).join(",");
console.log(_output);
Regular expressions should work. They are likely slower than writing your own loops, but in most cases they are clearer and you won't notice the difference.
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
console.info('original: ' + s);
var edited = s.replace(/¶.+¶/, '');
console.info('result: ' + edited);
var s = 'keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var t = s.split(",").filter(function(word) {
return !word.slice(-1).match(/[\u{0080}-\u{FFFF}]/gu, "");
})
console.info(t);
You can use the filter! Obviously this checks for any character that isn't ASCII. You can simply check if the last character is your ¶.
This way:
var str ='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var keywords = str.split(",");
for(keyword in keywords){
if(keywords[keyword].includes("¶")){
keywords.splice(keyword,1);
}
}
console.log(keywords);
PS: Every method loops to do it, you just can't see it in some forms ^^

url.replace with multiple replacements?

I've currently got the following to remove spaces and replace them with a hyphen.
How can I go about replacing a space with a hyphen and a dot with nothing and keep it in the same variable?
url = url.replace(/\s/g, '-');
url = url.replace(/\s/g, '-').replace(/\./g, ''); might do it.
I use this:
// This little gadget does replace for all not just first occurence like the native javascript function.
String.prototype.replaceAll = function(strTarget, strSubString){
var strText = this;
var intIndexOfMatch = strText.indexOf(strTarget);
while (intIndexOfMatch != -1){
strText = strText.replace(strTarget, strSubString);
intIndexOfMatch = strText.indexOf(strTarget);
}
return(strText);
}

get particular string part in javascript

I have a javascript string like "firstHalf_0_0_0" or secondHalf_0_0_0". Now I want to get the string before the string "Half" from above both strings using javascript.Please help me.
Thanks.
var myString = "firstHalf_0_0_0";
var parts = myString.split("Half");
var thePart = parts[0];
var str = 'firstHalf_0_0_0',
part = str.match(/(\w+)Half/)[1];
alert(part); // Alerts "first"
var str = "firstHalf.....";
var index = str.indexOf("Half");
var substring = str.substr(0, index);
jsFiddle demo.
Using this you can get any particular part of string.
var str= 'your string';
var result = str.split('_')[0];
Working example here for your particular case.
http://jsfiddle.net/7kypu/3/
cheers!

Categories

Resources