Remove space without using string method trim - javascript

How can I remove all the left space without removing between & the right space of the string? And also when I changed the value of str the result will be the same. Only the left space will be removed.
function trimLeftSpace() {
var str = " Angry Bird ";
var splitTrim = str.split('');
var trimStr = "";
for (var index = 0; index < splitTrim.length; index++) { //trim left space
if(splitTrim[index] != " ") {
trimStr += str[index];
}
}
return trimStr;
}

Your current solution creates a new string which contains all the non-space characters of the original string, you need to stop looking for spaces as soon as you find a non-space character. Here is an example:
function trimLeftSpace(str) {
var doneTrimming = false
var ret = ""
for (var index = 0; index < str.length; index++) {
if(str[index] !== ' '){
doneTrimming = true
}
if(doneTrimming){
ret += str[index]
}
}
return ret;
}
var result = trimLeftSpace(" Angry Bird ");
console.log("|"+result+"|");

To trim the beginning of the string, use a simple regex to replace the whitespaces in the beginning of the string:
var str = " Angry Bird ";
function trimLeftSpace(str) {
return str.replace(/^\s+/, '');
}
console.log('"' + trimLeftSpace(str) + '"');
Or just use .trimStart():
var str = " Angry Bird ";
function trimLeftSpace(str) {
return str.trimStart();
}
console.log('"' + trimLeftSpace(str) + '"');

You could try a regex replacement:
var str = " Angry Bird ";
str = str.replace( new RegExp("^\\s+", "gm"),"");
console.log('"' + str + '"');

This will remove all whitespace on the left of the string:
function trimLeftSpace(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
if(str[i] != " ") {
return str.slice(i);
break;
} else {
result += str[i];
}
}
return result;
}
console.log(trimLeftSpace(" Angry Birds Angry Birds"));

Try this
function trimLeftSpace(str) {
return str.replace(/\s+$/, '')
}
var result = trimLeftSpace(" Angry Bird ");
console.log("|"+result+"|");

If you want to use a function instead of regex solutions from the other answers, then make a function that looks for the first non-space character, then use slice to cut only the part of the string that's after it:
function customTrim(str) {
for(var i = 0; i < str.length; i++) {
if(str.charAt(i) !== " ") {
return str.slice(i);
}
}
}
var res = customTrim(" Snake Shot ");
console.log('"' + res + '"');
Notes:
This only looks for spaces ' '. If you want to look for tabs '\t', newlines '\n', ... then just add them to the if test (sperate them with &&).
If an empty or space-only strings are passed, then undefined is returned, if you don't want that then just return an empty string at the bottom of the function to make it the default return value.

You could try a regex replacement:
let variable = "hello world";
let removeRegex = /^\s+|\s+$/g;
let removeSpace = variable.replace(removeRegex,"");
console.log(removeSpace);

Related

use js change var str="are you okay" to are| you| okay|

var str="are you okay"
I want to change this str like this
are| you| okay|
Here is my code
function split() {
var str = "are you okay",
res = ""
var arr = str.trim().split(/\s+/)
for (i = 0; i < arr.length; i++) {
res += arr[i] + "|"
}
return res;
}
so I don't know how to return the result like are| you| okay|
There is a shorter solution. You can first remove double spaces:
var str = "are you okay";
var nospaces = str.replace(/\s+/g,' ').trim();
and then replace spaces with | :
var final_str = nospaces.replace(' ', '| ');
You could use combination of .split() to separate each space, .filter() to return words and .join() to merge them back into one word:
var str="are you okay";
const modifiedstr = `${str.split(/\s+/).filter(e=> e != '').join('| ')}|`;
console.log(modifiedstr);
This produces the desired output:
const split = (str) => str.trim().replace(/\s+/g, '| ') + '|';
If you want to continue that approach all you really need is map with a quick little join on the end:
function split(str) {
return str.trim().split(/\s+/).map(s => `${s}| `).join('').trim();
}
console.log(split("are you okay"));
Note that ES6 makes this pretty easy with template literals and arrow functions.
You could also do this with a simple regular expression if you're inclined:
function split(str) {
return str.replace(/\s+/g, '| ');
}
console.log(split("are you okay"));
Where here the /g flag means "global" as in "replace all instances". By default it will just do the first.
Your code look good you have to just do this:
function split() {
var str = "are you okay",
res = ""
var arr = str.trim().split(/\s+/)
for (i = 0; i < arr.length; i++) {
res += arr[i] + "| "; // add space after | sign
}
return res.trim(); // to remove last space
}
var string = split()
console.log(string)
Or you can do this:
function split(str) {
return str.trim().split(/\s+/).join('| ')+'|';
}
var str = "are you okay";
var result = split(str);
console.log(result)

Javascript - Search unicode string in unicode string

When i try to search a unicode string in a unicode string, i find no solution.
Ex: check if string 'vie' is contained in string 'Mr. ViỆt has a blue house'
So i try a hard way as below:
// Convert string to Unicode
function toUnicode(theString) {
var unicodeString = '';
for (var i=0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
// Convert string to be Regex Unicode
function toRegexUnicode(theString) {
var unicodeString = '';
for (var i=0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return new RegExp('[' + unicodeString + ']')
}
// Search
function searchUnicode() {
var strOriginal = "Mr. ViỆt has a blue house"
var regexUnicode = toRegexUnicode(strOriginal)
var strSearch = toUnicode('vie')
var result = regexUnicode.test(strSearch)
console.log(result)
}
Test at: https://www.w3schools.com/code/tryit.asp?filename=FY3NGXMQRMLA
Are there any better ways?
First, your regex expression is wrong. Remove the braces.
Second, you're creating your regex testing the wrong way around.
You're currently setting up your regex search using your full string.
You're also not converting your strOriginal to Unicode.
This means your searchUnicode function needs to appear as follows:
var strOriginal = "Mr. ViỆt has a blue house"
var strOriginalUnicode = toUnicode(strOriginal)
var strSearch = toUnicode('vie')
var regexUnicode = toRegexUnicode(strSearch)
var result = regexUnicode.test(strOriginalUnicode)
Next, we can simplify your toRegexUnicode function as such:
// Convert string to be Regex Unicode
function toRegexUnicode(theString) {
theString = theString.replace(/\\/g, "\\\\")
return new RegExp(theString)
}
No need to reuse your conversion method. You will also note global replacements of all \ to become \\. That's because Regex considers a backslash as an escape character so we need to escape our escape character.
I try another way, just convert all string to ASCII then search:
function stringToASCII(str) {
try {
return str.replace(/[àáảãạâầấẩẫậăằắẳẵặ]/g, 'a')
.replace(/[èéẻẽẹêềếểễệ]/g, 'e')
.replace(/[đ]/g, 'd')
.replace(/[ìíỉĩị]/g, 'i')
.replace(/[òóỏõọôồốổỗộơờớởỡợ]/g, 'o')
.replace(/[ùúủũụưừứửữự]/g, 'u')
.replace(/[ỳýỷỹỵ]/g, 'y')
} catch {
return ''
}
}
function searchASCII() {
var strOriginal = "Mr. ViỆt lê nguyễn thị tùng á à ạds"
var strSearch = "vie"
var strOriginalToASCII = stringToASCII(strOriginal.toLowerCase())
var strSearchToASCII = stringToASCII(strSearch.toLowerCase())
var result = strOriginalToASCII.includes(strSearchToASCII)
// Results
console.log('strOriginalToASCII: ', strOriginalToASCII)
console.log('strSearchToASCII: ', strSearchToASCII)
console.log('result: ', result)
}
Output:
strOriginalToASCII: mr. viet le nguyen thi tung a a ads
strSearchToASCII: vie
result: true
Test at: https://www.w3schools.com/code/tryit.asp?filename=FY3NGXMQRMLA

Why is my for loop using push inside a function not working?

I am trying to pass a phrase through a function so that every first letter is capitalized and everything else is lower case. I have the following function:
function titleCase(str) {
var array = [];
for (var i = 0; i <= str.length; i++) {
str = str.split(' ');
str = str[i].toLowerCase();
str = str.charAt(0).toUpperCase() + str.substr(1, str.length);
array = array.push(str);
return array.push(str);
}
}
titleCase("SenTencE TesT");
Without the for loop the function works and will lowercase everything and then capitalize the first letter of each word.
[EDIT]
A lot of ways to do it, but try this...
function titleCase(string) {
var array = string.split(' ');
var newString = '';
for (var i = 0; i <= array.length-1; i++) {
array[i] = array[i].toLowerCase();
array[i] = array[i].charAt(0).toUpperCase() + array[i].substr(1, array[i].length);
newString += array[i] + ' ';
};
return newString.trim();
};
console.log( titleCase("SenTencE TesT") );
1) Don't name your variable array, that is a JavaScript reserved word, you can use "arr" for example.
2) In your code you are splitting the sentence in to an array of words but you are only applying the toLowerCase to the first word.
3) There's a much cleaner way to achieve the result you want:
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
console.log( capitalize("sentence TesT") );
Hope it helps.

Reverse string to find palindromes in JavaScript

I have two strings. The first is normal string, the second I want to be a reversed string like first one, but in the console I didn't get the look of like first one listed by commas. How can I fix that ?
Normal string -
Revered string -
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
console.log(words);
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i];
}
console.log(newString);
}
}
If you really just want to find out if a string is a palindrome, you can do something as simple as this:
function isPalindrome(str) {
return str.toLowerCase() === str.toLowerCase().split('').reverse().join('');
}
The first for loop is not necessary. You do not need to concatenate a space character " " to the element of the array, where the variable assignment i
var i = 0;
and condition
i < words.length - 1;
stops before reaching last element of array.
var newString = "";
for (var i = words.length - 1; i >= 0; i--) {
newString += words[i] + " ";
}
console.log(newString);
In your "normal" string example, you're printing words to the console. Let's first look at what words is: var words = str.split(" ");
The String.split() function returns an array of strings. So your "normal" string is actually an array of strings (The brackets [] and comma separated strings in the console output indicate this).
In the second example, you're logging newString. Let's look at where it comes from: var newString = "";
newString is a String. If you want it to be an array of strings like words, you would declare it with var newString = [];. Arrays do not support += so newString += words[i]; would become newString.push(words[i]);
The above explains how to get newString to behave like words, the code you've written is not looking for a palindrome word, but rather a palindrome sentence: "Bob is Bob" is not a palindrome (reversed it is "boB si boB") but it could be a Palindrome sentence (if such a thing exists).
Thanks to all, I wrote this solution for the problem. I hope this is the right answer.
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
btn.addEventListener("click",function(event){
event.preventDefault();
findPalindromes(inputBox.value);
});
str = inputBox.value;
function findPalindromes(str) {
var words = str.split(" "),
newString = [];
for (var i = 0; i < words.length - 1; i++) {
if ((words[i] === words[i].split('').reverse().join('')) === true) {
newString.push(words[i]);
}
}
console.log(newString);
}
}
var words = " ";
function reverse_arr(arr){
var i = arr.length - 1;
while(i >= 0){
words += a[i] + " ";
i--;
}
return words;
}

How to get unmatched keywords?

I am using this as keyword s='young girl jumping'
function selfreplace(s) {
var words = ['man', 'jumping'];
var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s)) {
str += match[0] + '(k)';
}
return str;
}
It is returning jumping(k)
I want the result to be young(s) girl(s) jumping(k)
It would probably be easiest to check if it's in words outside of the regex:
function selfreplace(s) {
var words = ['man','jumping'];
var re = new RegExp('\\b(\\w+)\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s))
{
if (words.indexOf(match[0]) !== -1))
str += match[0] + '(k)';
else
str += match[0] + '(s)';
}
return str;
}
You can use a replace with callback.
function selfreplace(s){
return s.replace(/man|jumping|(\w+)/g, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
If the word matched is man or jumping, only the first argument (entire match) is set. If the word matched is any other, the first capturing group is set as well.
If you don't know the set of words ahead, you can still generate the regex on the fly. Assuming words don't contain non-word characters:
function selfreplace(s, words){ //or any other method of passing 'words'
var re = RegExp(words.join("|")+"|(\\w+)",'g');
return s.replace(re, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
Just a different approach, probably not the best solution but thought i'd throw it out there.
var str = "young girl jumping";
function replaceStr(s){
var matched = new RegExp("man|jumping", "i");
var newStr = "";
var str = s.split(" ");
for(var i=0; i<str.length;i++){
if(str[i].match(matched)){
newStr += str[i]+"(k) ";
} else {
newStr += str[i]+"(s) ";
}
}
return newStr.substr(0, newStr.length-1);
}
//replaceStr(str) returns "young(s) girl(s) jumping(k)"
DEMO here
if the matched words might change then you can always amend this function so it accepts an array as the second argument and then creates the regexp dynamically
replaceStr(s, matchArr){} and
var matched = new RegExp("("+matchArr.join("|")+")", "i");
Something like this might give you a hint:
var s = "young girl jumping",
words = ['man','jumping'],
regex = new RegExp("(" + words.join("|") +")", "g"),
q = s.replace(regex, function( string ) {
return string + "(k)";
});
console.log(q); // "young girl jumping(k)"
If you match words only, you do not really need regexps at all, do you?
What about just looking for the words with ==
function selfreplace(s) {
var words = ['man','jumping'];
var input = s.split(" ");
var str = "";
for(var i=0; i<input.length; i++){
var tmpString = "(s)";
for(var j=0; j<words.length; j++){
if(input[i] == words[j]){
tmpString = "(k)";
}
}
str += input[i]+tmpString;
}
return str;
}
You could use a RegExp for this, but for what you are doing a RegExp is overkill. I would use Array methods instead:
var selfreplace = function selfreplace(s) {
var words = ['man', 'jumping'],
i = 0,
suffix = '(s)';
s = s.split(' ');
for (i = 0; i < s.length; i += 1) {
if (words.indexOf(s[i]) > -1) {
s[i] = s[i] + '(k)';
} else {
s[i] = s[i] + '(s)';
}
}
return s.join(' ');
};
Here's a fiddle in action: http://jsfiddle.net/4KAzw/

Categories

Resources