regex replace all leading spaces with something - javascript

I'm trying to replace all of the leading spaces in a string with something
Here's what I tried so far
var str = ' testing 1 2 3 ',
regex = /^\s*/,
newStr = str.replace(regex, '.');
document.write(newStr)
I want to get a result like:
'.....testing 1 2 3 '
Is there something I'm missing?

Try this:
var s = " a b c";
print(s.replace(/^\s+/, function(m){ return m.replace(/\s/g, '.');}));
which prints:
...a b c

Alternative (ignores strnigs w/ no non-space)
var newStr = "";
newStr = (newStr = Array(str.search(/[^\s]/) + 1).join(".")) + str.substr(newStr.length);

What about:
/^([ ]+)/
I'm not sure \s does the trick, while a plain should be able to handle this!

This is even shorter.
var text = " a b c";
var result = s.replace(/\s/gy, ".");
console.log(result); // prints: "...a b c";
Why it works was explained for me here.

Related

Count words input field

Basically I need to get the number of words in an input field. So the approach is to trim the leading and trailing spaces and also to limit the remaining spaces within the string to 1. So that I'll be able to get the number of words. Below is my code to do this.
E.g.
input value:
" Robert Neil Cook "
Expected output:
3 //"Robert Neil Cook"
This is what I tried.
var str = $.trim( $('#inval').val() );
var Fstr = str.split(' ').length;
console.log(fstr);
You can use below custom function for count words
function countWords(s){
s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude start and end white-space
s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
return s.split(' ').length;
}
alert(countWords("How are you?"));
Try below :
str= " Robert Neil Cook " ;
str = $.trim(str.replace(/ +(?= )/g,'')); // replace multiple spaces to single space
console.log(str)
var words = str.split(' '); // count the no of words using .split() method
alert(words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
You can use .match(/\S+/g):
var str = " Robert Neil Cook ";
var arr = str.match(/\S+/g);
var newstr = arr.join()
console.log('length::::>', arr.length);
console.log('newstr::::>', newstr);
This .match(/\S+/g) would return you the words without any space as an array and you can use length property of it.
Try this code..
var str = $.trim( $('#inval').val() );
var words = str.split(' ').filter(v=>v!='').length;
You can Haresh Vidja's function more compact like this
function countWords(s){
return s.trim().replace(/[ ]{2,}/gi," ").split(" ").length;
}
console.log(countWords("some words here")
Please have a look attached snippet.
var str = $.trim( $('#inval').val() );
str1 = str.replace(/ +(?= )/g,'')
var fstr = str1.split(' ').length;
console.log(fstr);
console.log(str1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value=" Robert Neil Cook " id="inval">
Very simple solution, try this
var str = " Robert Neil Cook ";
str = str.trim();
var str = str.split(' ').join('');
var fstr = str.split(' ').length;
console.log(fstr);

Javascript - remove a string in the middle of a string

Thank you everyone for your great help !
Sorry, I have to edit my question.
What if the "-6.7.8" is a random string that starts with "-" and has two "." between random numbers? such as "-609.7892.805667"?
===============
I am new to JavaScript, could someone help me for the following question?
I have a string AB.CD.1.23.3-609.7.8.EF.HI
I would like to break it into two strings: AB.CD.1.2.3.EF.HI (remove -609.7.8 in the middle) and AB.CD.6.7.8.EF.HI (remove 1.23.3- in the middle).
Is there an easy way to do it?
Thank you very much!
var s = "AB.CD.1.23.3-609.7.8.EF.HI";
var a = s.replace("-609.7.8","");
var b = s.replace("1.23.3-","");
console.log(a); //AB.CD.1.23.3.EF.HI
console.log(b); //AB.CD.609.7.8.EF.HI
You could use
str.replace();
var str = "AB.CD.1.2.3-6.7.8.EF.HI";
var str1 = str.replace("-6.7.8",""); // should return "AB.CD.1.2.3.EF.HI"
var str2 = str.replace("1.2.3-",""); // should return "AB.CD.6.7.8.EF.HI"
Use split() in String.prototype.split
var myString = "AB.CD.1.23.3-609.7.8.EF.HI";
var splits1 = myString.split("-609.7.8");
console.log(splits1);
var splits2 = myString.split("1.23.3-");
console.log(splits2);
With regular expressions:
s = 'AB.CD.1.23.3-609.7.8.EF.HI'
var re = /([A-Z]+\.[A-Z]+)\.([0-9]+\.[0-9]+.[0-9]+)-([0-9]+\.[0-9]+.[0-9]+)\.([A-Z]+\.[A-Z]+)/
matches = re.exec(s)
a = matches[1] + '.' + matches[2] + '.' + matches[4] // "AB.CD.1.23.3.EF.HI"
b = matches[1] + '.' + matches[3] + '.' + matches[4] // "AB.CD.609.7.8.EF.HI"

Replacing the last character in a string javascript

How do we replace last character of a string?
SetCookie('pre_checkbox', "111111111111 11 ")
checkbox_data1 = GetCookie('pre_checkbox');
if(checkbox_data1[checkbox_data1.length-1]==" "){
checkbox_data1[checkbox_data1.length-1]= '1';
console.log(checkbox_data1+"after");
}
out put on console : 111111111111 11 after
Last character was not replaced by '1' dont know why
also tried : checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-1), "1");
could some one pls help me out
Simple regex replace should do what you want:
checkbox_data1 = checkbox_data1.replace(/.$/,1);
Generic version:
mystr = mystr.replace(/.$/,"replacement");
Remember that just calling str.replace() doesn't apply the change to str unless you do str = str.replace() - that is, apply the replace() function's return value back to the variable str
use regex...
var checkbox_data1 = '111111111111 11 ';
checkbox_data1.replace(/ $/,'$1');
console.log(checkbox_data1);
This will replace the last space in the string.
You have some space in our string please try it
checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-4), "1 ");
then add the space in
console.log(checkbox_data1+" after");
This is also a way, without regexp :)
var string = '111111111111 11 ';
var tempstr = '';
if (string[string.length - 1] === ' ') {
for (i = 0; i < string.length - 1; i += 1) {
tempstr += string[i];
}
tempstr += '1';
}
You can try this,
var checkbox_data1=checkbox_data1.replace(checkbox_data1.slice(-1),"+");
This will replace the last character of Your string with "+".
As Rob said, strings are immutable. Ex:
var str = "abc";
str[0] = "d";
console.log(str); // "abc" not "dbc"
You could do:
var str = "111 ";
str = str.substr(0, str.length-1) + "1"; // this makes a _new_ string

Remove a character at a certain position in a string - javascript [duplicate]

This question already has answers here:
How can I remove a character from a string using JavaScript?
(22 answers)
Closed 5 years ago.
Is there an easy way to remove the character at a certain position in javascript?
e.g. if I have the string "Hello World", can I remove the character at position 3?
the result I would be looking for would the following:
"Helo World"
This question isn't a duplicate of How can I remove a character from a string using JavaScript?, because this one is about removing the character at a specific position, and that question is about removing all instances of a character.
It depends how easy you find the following, which uses simple String methods (in this case slice()).
var str = "Hello World";
str = str.slice(0, 3) + str.slice(4);
console.log(str)
You can try it this way:
var str = "Hello World";
var position = 6; // its 1 based
var newStr = str.substring(0, position - 1) + str.substring(position, str.length);
alert(newStr);
Here is a live example: http://jsbin.com/ogagaq
Turn the string into array, cut a character at specified index and turn back to string
let str = 'Hello World'.split('')
str.splice(3, 1)
str = str.join('')
// str = 'Helo World'.
If you omit the particular index character then use this method
function removeByIndex(str,index) {
return str.slice(0,index) + str.slice(index+1);
}
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));
// Output: "Helo world"
var str = 'Hello World';
str = setCharAt(str, 3, '');
alert(str);
function setCharAt(str, index, chr)
{
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
you can use substring() method. ex,
var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
Hi starbeamrainbowlabs ,
You can do this with the following:
var oldValue = "pic quality, hello" ;
var newValue = "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);
I tested this in my javascript console so you can also check this out
Thanks
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i should not be less then 1.

Replace last occurrence of character in string

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c';
console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
This will replace it with the contents of the variable replacement:
var str = 'a_b_c',
replacement = '!';
console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"
// Replace last char in a string
console.log(
str1.substring(0,str1.length-2)+"?"
)
// alternative syntax
console.log(
str1.slice(0,-1)+"?"
)
// Replace last underscore in a string
var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax
console.log(
str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)
What about this?
function replaceLast(x, y, z){
var a = x.split("");
a[x.lastIndexOf(y)] = z;
return a.join("");
}
replaceLast("Hello world!", "l", "x"); // Hello worxd!
Another super clear way of doing this could be as follows:
let modifiedString = originalString
.split('').reverse().join('')
.replace('_', '')
.split('').reverse().join('')
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
var someString = "(/n{})+++(/n{})---(/n{})$$$";
var toRemove = "(/n{})"; // should find & remove last occurrence
function removeLast(s, r){
s = s.split(r)
return s.slice(0,-1).join(r) + s.pop()
}
console.log(
removeLast(someString, toRemove)
)
Breakdown:
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
Reverse the string, replace the char, reverse the string.
Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?
// Define variables
let haystack = 'I do not want to replace this, but this'
let needle = 'this'
let replacement = 'hey it works :)'
// Reverse it
haystack = Array.from(haystack).reverse().join('')
needle = Array.from(needle).reverse().join('')
replacement = Array.from(replacement).reverse().join('')
// Make the replacement
haystack = haystack.replace(needle, replacement)
// Reverse it back
let results = Array.from(haystack).reverse().join('')
console.log(results)
// 'I do not want to replace this, but hey it works :)'
This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array)
Anyway, I just thought I'd put it out there in case someone prefers it.
var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'
The '_' can be swapped out with the char you want to replace
And the '-' can be replaced with the char or string you want to replace it with
You can use this code
var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);
alert(str);
This is a recursive way that removes multiple occurrences of "endchar":
function TrimEnd(str, endchar) {
while (str.endsWith(endchar) && str !== "" && endchar !== "") {
str = str.slice(0, -1);
}
return str;
}
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)

Categories

Resources