Javascript 方法或方法来获取字符串中的相邻字符

发布于 2024-09-30 15:33:26 字数 241 浏览 2 评论 0原文

尝试获取字符串中包含空格的相邻字符。左侧 3 个字符和右侧 3 个字符...

也许使用正则表达式和 JavaScript split() 来获取字符串中的相邻字符?

var str   = "one two three four five",
array     = str.split("");

但缺少空格以及左侧 3 个字符和右侧 3 个字符...

有什么建议吗?

Trying to get adjacent characters in a string including blank spaces. the 3 characters to the left and the 3 characters to the right...

maybe using regular expressions and JavaScript split() to get adjacent characters in string?

var str   = "one two three four five",
array     = str.split("");

but missing the blank spaces and the 3 character to the left and the 3 characters to the right...

any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

童话 2024-10-07 15:33:26

你尝试过JS子字符串吗

var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));

http://www.w3schools.com/jsref/jsref_substring.asp

或者类似查找位置

http://phpjs.org/functions/strpos:545

Did you try JS substring

Something like this

var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));

http://www.w3schools.com/jsref/jsref_substring.asp

Or something like finding position

http://phpjs.org/functions/strpos:545

余生一个溪 2024-10-07 15:33:26

我假设您正在寻找 indexOf 和 substr 的组合

,这是一个示例函数,它返回一个包含左、右和错误(如果有)的对象,

    function findSurrounding(needle, haystack, leadingCharacters, trailingCharacters){
        var pos = haystack.indexOf(needle);
        var returnObject = {'left':'', 'right':'', 'error':null};

        //if needle was not found, output error
        if(pos == -1){
            returnObject.error = needle + ' could not be found!';

        //otherwise set "left" and "right"
        } else {
            returnObject.left = haystack.substr(pos - leadingCharacters, leadingCharacters);
            returnObject.right = haystack.substr(pos + needle.length, trailingCharacters);
        }
        return returnObject;
    }
    //get output:
    var surrounding = findSurrounding('three', 'one two three four five', 3, 3)
    //debug / write output
    for(prop in surrounding){
        document.write(prop+': '+surrounding[prop]+'<br/>');
    }

其输出

left: wo 
right:  fo
error: null

希望有所帮助(另外希望我理解您的问题!)

I assume you're looking for a combination of indexOf and substr

Here's an example function that returns an object containing left, right and error (if any)

    function findSurrounding(needle, haystack, leadingCharacters, trailingCharacters){
        var pos = haystack.indexOf(needle);
        var returnObject = {'left':'', 'right':'', 'error':null};

        //if needle was not found, output error
        if(pos == -1){
            returnObject.error = needle + ' could not be found!';

        //otherwise set "left" and "right"
        } else {
            returnObject.left = haystack.substr(pos - leadingCharacters, leadingCharacters);
            returnObject.right = haystack.substr(pos + needle.length, trailingCharacters);
        }
        return returnObject;
    }
    //get output:
    var surrounding = findSurrounding('three', 'one two three four five', 3, 3)
    //debug / write output
    for(prop in surrounding){
        document.write(prop+': '+surrounding[prop]+'<br/>');
    }

output of this is

left: wo 
right:  fo
error: null

Hope that helps (additionally hope I understood your question!)

万水千山粽是情ミ 2024-10-07 15:33:26

我在这里添加另一个答案,因为我相信我原来的答案确实回答了您的问题(如何获取相邻字符)。

但是,在您发布代码后,我看到您想创建一个放大镜。这有点不同,所以我重写了你的代码。

不同的原因是您需要使用鼠标悬停来获取单个字母,这意味着您必须将单个字母封装到标签中。发布的代码就是这样做的(本质上是代码的工作版本。)注意我没有弄乱你的可拖动。如果您对新问题的时间有疑问。

<style type="text/css">
        body { font-family:"Tiresias PCfont Z"; /* font-size:15px; */ background: #fff; line-height:1.1em; }
        .draggable { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
        #draggable { margin-bottom:20px; }
        #MagDrag {background-image:url(controls/MagLens1.png); width: 236px; height: 73px; }
        #containment-wrapper { width: 95%; height:150px; border:2px solid #ccc; padding: 10px; display:none;}
        #magnifyView { width: 90px;
            background-image:url(controls/MagLens1.png);width: 212px;height: 50px; white-space: nowrap; font-size: 40px; font-weight:bold;
        }
        .onText { color:#990000;}
    </style>
    <script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.java2s.com/Tutorial/JavaScriptDemo/js/ui/ui.core.js"></script>
    <script type="text/javascript" src="http://www.java2s.com/Tutorial/JavaScriptDemo/js/ui/ui.draggable.js"></script>
    <script type="text/javascript" charset="utf-8">
        //custom "magnify" function
        var mag = function(){
            return {
                add: function(){
                    //encapsulate #article into individual spans
                    //why?  mouseover events are triggered by tags, not individual letters
                    var str = $('#article').text();
                    var output = '';
                    for(var i = 0; i<str.length; i++){
                        output += '<span>' + str.substr(i, 1) + '</span>';
                    }
                    //replace #article with altered html
                    $('#article').html(output);

                    //add the mouseover
                    $('#article span').mouseover(function(){
                        //note both these selectors could be way more efficient
                        //however this should get you started...
                        var leading = $(this).prev().add($(this).prev().prev()).add($(this).prev().prev().prev());
                        var trailing = $(this).next().add($(this).next().next()).add($(this).next().next().next());

                        $('#magnifyView').html(
                            $(leading).text() +
                            '<span class="onText">' + $(this).text() + '</span>' +
                            $(trailing).text()
                        );
                    });
                    $('#containment-wrapper').show();
                },
                remove: function(){
                    $('#article span').unbind('mouseover');
                    $('#article').html($('#article').text());
                    $('#containment-wrapper').hide();
                }
            }
        }();

        // jquery $ function load
        $(document).ready(function(){
            $('.addmag').click(function(){
                mag.add();
            });
            $('.removemag').click(function(){
                mag.remove();
            });
            $("#magnifyView").draggable({ containment: '#containment-wrapper', scroll: false, axis: 'x' });
        });
    </script>

请注意,您需要单击“addmag”或“removemag”来添加或删除放大镜功能。 (这是为了演示如何使用 jquery 和基本循环封装字符串,以及如何获取原始字符串、保留空格等。)

希望有所帮助!

I'm adding another answer here because I believe my original answer really does answer your question as stated (how to get adjacent characters).

However after you posted your code I see you want to create a magnifier. That's kinda a different kettle of fish so I rewrote your code.

The reason it's different is then you need to use the mouseover to get individual letters and that means you must encapsulate individual letters into tags. The code posted does that (essentially a working version of your code.) Note I didn't mess with your draggable. If you're having issues with that time for a new question.

<style type="text/css">
        body { font-family:"Tiresias PCfont Z"; /* font-size:15px; */ background: #fff; line-height:1.1em; }
        .draggable { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
        #draggable { margin-bottom:20px; }
        #MagDrag {background-image:url(controls/MagLens1.png); width: 236px; height: 73px; }
        #containment-wrapper { width: 95%; height:150px; border:2px solid #ccc; padding: 10px; display:none;}
        #magnifyView { width: 90px;
            background-image:url(controls/MagLens1.png);width: 212px;height: 50px; white-space: nowrap; font-size: 40px; font-weight:bold;
        }
        .onText { color:#990000;}
    </style>
    <script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.java2s.com/Tutorial/JavaScriptDemo/js/ui/ui.core.js"></script>
    <script type="text/javascript" src="http://www.java2s.com/Tutorial/JavaScriptDemo/js/ui/ui.draggable.js"></script>
    <script type="text/javascript" charset="utf-8">
        //custom "magnify" function
        var mag = function(){
            return {
                add: function(){
                    //encapsulate #article into individual spans
                    //why?  mouseover events are triggered by tags, not individual letters
                    var str = $('#article').text();
                    var output = '';
                    for(var i = 0; i<str.length; i++){
                        output += '<span>' + str.substr(i, 1) + '</span>';
                    }
                    //replace #article with altered html
                    $('#article').html(output);

                    //add the mouseover
                    $('#article span').mouseover(function(){
                        //note both these selectors could be way more efficient
                        //however this should get you started...
                        var leading = $(this).prev().add($(this).prev().prev()).add($(this).prev().prev().prev());
                        var trailing = $(this).next().add($(this).next().next()).add($(this).next().next().next());

                        $('#magnifyView').html(
                            $(leading).text() +
                            '<span class="onText">' + $(this).text() + '</span>' +
                            $(trailing).text()
                        );
                    });
                    $('#containment-wrapper').show();
                },
                remove: function(){
                    $('#article span').unbind('mouseover');
                    $('#article').html($('#article').text());
                    $('#containment-wrapper').hide();
                }
            }
        }();

        // jquery $ function load
        $(document).ready(function(){
            $('.addmag').click(function(){
                mag.add();
            });
            $('.removemag').click(function(){
                mag.remove();
            });
            $("#magnifyView").draggable({ containment: '#containment-wrapper', scroll: false, axis: 'x' });
        });
    </script>

Note, you'll need to click the "addmag" or "removemag" to add or remove the magnifier functionality. (This is there to demonstrate how to encapsulate a string using jquery and a basic loop as well as how to get the original string back, preserving spaces etc.)

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文